这是一个非常小的例子:
class Foo
{
public:
Foo(int x) {};
};
void ProcessFoo(Foo& foo)
{
}
int main()
{
ProcessFoo(Foo(42));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
以上编译在Visual Studio上很好,但在Linux和Mac上生成错误.
编译上面会生成这个:
$ g++ -std=c++11 -c newfile.cpp
newfile.cpp: In function ‘int main()’:
newfile.cpp:23:23: error: invalid initialization of non-const reference of type ‘Foo&’ from an rvalue of type ‘Foo’
ProcessFoo(Foo(42));
^
newfile.cpp:14:6: note: in passing argument 1 of ‘void ProcessFoo(Foo&)’
void ProcessFoo(Foo& foo)
Run Code Online (Sandbox Code Playgroud)
我找到了三个解决方法:
像这样:
Foo foo42(42);
ProcessFoo(foo42);
Run Code Online (Sandbox Code Playgroud)
ProcessFoo采用const引用: void ProcessFoo(const Foo& foo)
ProcessFoo只是让Foo按值传递. void ProcessFoo(Foo foo)
为什么编译器禁止我的原始代码?(这是什么防守)?上面三个满足编译器的解决方法中的每一个都有什么用?MSVC会允许什么,但不是g …