C++创建临时对象来调用成员函数



下面代码中有编译错误的代码行(注释中(出了什么问题?我以为它应该用const std::string调用TestMe构造函数,然后在它上面调用operator()。但看起来它试图用变量a构造TestMe

#include <iostream>
namespace
{
class TestMe
{
public:
TestMe() {}
TestMe( const std::string& me ) : me_( me ) {}
bool operator()() const
{
std::cout << "calling operator()" << std::endl;
return true;
}
private:
const std::string me_;
};
}

int main()
{
const std::string a("a");
//
// construct an instance of TestMe and call its operator()
//
TestMe()();         // OK
TestMe( "abc" )();  // OK
TestMe tm( a );     // OK
TestMe( a )();      // compile error: what's wrong with this?
TestMe( { a } )();  // OK
return 0;
}

编译错误:

../src/main.cpp: In function ‘int main()’:
../src/main.cpp:44:14: error: ‘{anonymous}::TestMe a()’ redeclared as different kind of symbol
TestMe( a )();   // compile error
^
../src/main.cpp:35:20: note: previous declaration ‘const string a’
const std::string a("a");

"最令人烦恼的解析":https://www.fluentcpp.com/2018/01/30/most-vexing-parse/

TestMe( a )()被视为名为a的函数的声明,该函数不接受参数并返回TestMe对象。

稍微更改您的程序,使有问题的行不会与名称a:冲突

#include <iostream>
namespace
{
class TestMe
{
public:
TestMe() {}
TestMe( const std::string& me ) : me_( me ) {}
bool operator()() const
{
std::cout << "calling operator()" << std::endl;
return true;
}
private:
const std::string me_;
};
}

int main()
{
const std::string a("a");
//
// construct an instance of TestMe and call its operator()
//
TestMe()();         // OK
TestMe( "abc" )();  // OK
TestMe tm( a );     // OK
std::cout << "before most vexing parsen";
TestMe( b )();      // compiles, but has no effect
std::cout << "after most vexing parsen";
TestMe( { a } )();  // OK
return 0;
}

您将看到TestMe( b )();行没有输出,因为它只是一个声明:

calling operator()
calling operator()
before most vexing parse
after most vexing parse
calling operator()

最新更新