相关疑难解决方法(0)

无法传递临时对象作为参考

这是一个非常小的例子:

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)

我找到了三个解决方法:

  1. 避免使用内联临时变量来调用ProcessFoo.

像这样:

Foo foo42(42);
ProcessFoo(foo42);
Run Code Online (Sandbox Code Playgroud)
  1. ProcessFoo采用const引用: void ProcessFoo(const Foo& foo)

  2. ProcessFoo只是让Foo按值传递. void ProcessFoo(Foo foo)

为什么编译器禁止我的原始代码?(这是什么防守)?上面三个满足编译器的解决方法中的每一个都有什么用?MSVC会允许什么,但不是g …

c++ visual-c++ c++11

17
推荐指数
2
解决办法
1万
查看次数

标签 统计

c++ ×1

c++11 ×1

visual-c++ ×1