C++ function definition and variable declaration mismatch?

后端 未结 1 801
广开言路
广开言路 2021-01-19 08:12

Consider this very simple code:

#include 

class Foo
{
public:
    Foo() {};
};

class Bar
{
public:
    Bar( const std::shared_ptr&         


        
相关标签:
1条回答
  • 2021-01-19 08:55

    This issue is about C++'s most vexing parse. The statement:

    Bar bar( std::shared_ptr<Foo>( foo ) );
    

    declares a function called bar that returns Bar and takes an argument called foo of type std::shared_ptr<Foo>.

    The innermost parenthesis have no effect. It is as if you would have written the following:

    Bar bar( std::shared_ptr<Foo> foo);
    

    Assuming C++11 (since you are already using std::shared_ptr) you could use the brace syntax instead of parenthesis:

    Bar bar(std::shared_ptr<Foo>{foo});
    

    This would actually construct an object bar of type Bar, since the statement above can't be interpreted as a declaration because of the braces.

    0 讨论(0)
提交回复
热议问题