考虑以下非常简单的代码:
Consider this very simple code:
#include <memory> class Foo { public: Foo() {}; }; class Bar { public: Bar( const std::shared_ptr<Foo>& foo ) {} }; int main() { Foo* foo = new Foo; Bar bar( std::shared_ptr<Foo>( foo ) ); return 0; }为什么Visual Studio报告
Why does Visual Studio reports
warning C4930: 'Bar bar(std::shared_ptr<Foo>)': prototyped function not called (was a variable definition intended?)并且没有创建 bar 对象...此行 Bar bar(std :: shared_ptr< Foo>(foo)); 怎么解释为函数定义?
and there is no bar object created...how can this line Bar bar( std::shared_ptr<Foo>( foo ) ); be interpreted as a function definition?
我检查了做括号类型名称之后是否与new有所不同?以及 C ++:警告:C4930:未调用原型函数(是否打算使用变量定义?),但是我觉得这里的问题有所不同,因为我没有使用语法 Foo()或 Bar().
I checked Do the parentheses after the type name make a difference with new? and also C++: warning: C4930: prototyped function not called (was a variable definition intended?), but I feel my problem is different here as I did not use the syntax Foo() nor Bar().
请注意,它可以成功编译:
Note that it successfully compiles:
Foo* foo = new Foo; std::shared_ptr<Foo> fooPtr( foo ); Bar bar( fooPtr ); 推荐答案此问题与 C ++最令人讨厌的解析有关.声明:
Bar bar( std::shared_ptr<Foo>( foo ) );声明一个名为 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);假设使用C ++ 11(因为您已经在使用 std :: shared_ptr ),则可以使用括号语法代替括号:
Bar bar(std::shared_ptr<Foo>{foo});这实际上将构造一个类型为 Bar 的对象 bar ,因为上面的语句由于括号不能被解释为声明.
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.
更多推荐
C ++函数定义和变量声明不匹配?
发布评论