代码之家  ›  专栏  ›  技术社区  ›  Björn Pollex

编译器抱怨构造函数上的BOOST\u CHECK\u THROW

  •  5
  • Björn Pollex  · 技术社区  · 15 年前

    以下内容未编译:

    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
    

    1 回复  |  直到 15 年前
        1
  •  13
  •   Adam Bowen    15 年前

    这是因为 BOOST_CHECK_THROW Foo(bar) 正在扩展为语句。编译器看到该语句并将其解释为变量声明 Foo bar; 它需要一个默认构造函数。

    解决方案是为变量命名:

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

    换句话说 将扩展到类似

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

    Foo(bar); 作为一个名为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’