Bjö*_*lex 6 c++ constructor default-constructor boost-test
以下内容无法编译:
class Foo {
public:
Foo( boost::shared_ptr< Bar > arg );
};
// in test-case
boost::shared_ptr< Bar > bar;
BOOST_CHECK_THROW( Foo( bar ), std::logic_error ); // compiler error here
Run Code Online (Sandbox Code Playgroud)
Bar的实施无关紧要.编译器抱怨说,Foo没有合适的默认构造函数(VC++ 2005).如果我添加一个默认构造函数,它就可以工作,并且它实际上被调用了.为什么这个语句需要一个默认的构造函数?
Ada*_*wen 13
发生这种情况是因为它BOOST_CHECK_THROW是一个宏,并且Foo(bar)正在扩展为一个语句.编译器会看到此语句并将其解释为Foo bar;需要默认构造函数的变量声明.
解决方案是给变量一个名称:
BOOST_CHECK_THROW( Foo temp( bar ), std::logic_error );
Run Code Online (Sandbox Code Playgroud)
换句话说,BOOST_CHECK_THROW将扩展到类似的东西
try
{
Foo(bar);
// ... fail test ...
}
catch( std::logic_error )
{
// ... pass test ...
}
Run Code Online (Sandbox Code Playgroud)
并且编译器将解释Foo(bar);为名为bar的变量的声明.可以通过一个简单的程序来检查:
struct Test
{
Test(int *x) {}
};
int main()
{
int *x=0;
Test(x);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这给出了g ++的以下错误
test.cpp: In function ‘int main()’:
test.cpp:10: error: conflicting declaration ‘Test x’
test.cpp:9: error: ‘x’ has a previous declaration as ‘int* x’
Run Code Online (Sandbox Code Playgroud)