2010-03-03 94 views
3

BOOST_CHECK_THROW以下不会编译:编译器会抱怨构造

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 

酒吧的实现并不重要。编译器抱怨,Foo没有合适的默认构造函数(VC++ 2005)。如果我添加一个默认的构造函数,它会起作用,并且它实际上被调用。为什么这个语句需要一个默认的构造函数?

回答

9

发生这种情况是因为BOOST_CHECK_THROW是一个宏,并且Foo(bar)正在扩展为语句。编译器会看到这个语句并将其解释为需要默认构造函数的变量声明Foo bar;

的解决方案是给变量名:

BOOST_CHECK_THROW(Foo temp(bar), std::logic_error); 

换句话说BOOST_CHECK_THROW将扩大到像

try 
{ 
    Foo(bar); 
    // ... fail test ... 
} 
catch(std::logic_error) 
{ 
    // ... pass test ... 
} 

和编译器解释Foo(bar);作为变量称为声明酒吧。我们可以用一个简单的程序检查:

struct Test 
{ 
    Test(int *x) {} 
}; 

int main() 
{ 
    int *x=0; 
    Test(x); 
    return 0; 
} 

这给下面的错误使用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’ 
+0

的确。谢谢。 – 2010-03-03 14:38:44

相关问题