无法将临时对象作为引用传递 [英] Can't pass temporary object as reference

查看:169
本文介绍了无法将临时对象作为引用传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常小的例子:

This is a very minimal example:

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

void ProcessFoo(Foo& foo)
{
}

int main()
{
    ProcessFoo(Foo(42));
    return 0;
}

上述在Visual Studio上编译正常,但在Linux和Mac上生成错误。

The above compiles fine on Visual Studio, but generates an error on Linux and Mac.

编译以上内容会产生以下结果:

Compiling the above generates this:

$ 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)

我找到了三种解决方法:

I've found three workarounds:


  1. 避免在调用ProcessFoo时使用内联的临时变量。
    Foo foo42(42);
    ProcessFoo(foo42);

  1. Avoid the use of an inline a temp variable for the invocation of ProcessFoo. Foo foo42(42); ProcessFoo(foo42);

ProcessFoo使用一个常量引用: void ProcessFoo(const Foo& foo)

ProcessFoo takes a const reference: void ProcessFoo(const Foo& foo)

ProcessFoo只是让Foo传递值。 void ProcessFoo(Foo foo)

ProcessFoo just lets Foo get passed by value. void ProcessFoo(Foo foo)

禁止我的原始代码? (什么是守卫对抗)?上面三种满足编译器的解决方法是什么? MSVC允许它,但不是g ++?

Why is the compiler forbidding my original code? (What is it guarding against)? What is it about each of the three workarounds above that satisfies the compiler? What would MSVC allow it, but not g++?

推荐答案

通过设计,C ++只允许将一个临时变量传递给一个const引用,值或右值引用。想法是,一个函数接受一个非const引用参数,说明它想修改参数,并允许它回到调用者。用临时文件这样做是无意义的,很可能是一个错误。

By design, C++ only allows a temporary to be passed to a const reference, value, or rvalue reference. The idea is that a function taking a non-const reference parameter is stating that it wants to modify the parameter and allowing it to go back to the caller. Doing so with a temporary is meaningless and most likely an error.

我不知道你正在运行的是什么版本的g ++。它在此处不起作用: http://coliru.stacked-crooked.com/a/43096cb398cbc973

And I don't know what version of g++ you're running. It doesn't work here: http://coliru.stacked-crooked.com/a/43096cb398cbc973

这篇关于无法将临时对象作为引用传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆