0

据我所知,将左值绑定到右值引用是无效的。其次,左值表达式可以通过地址运算符 (&) 作为前缀来识别

如果这两个句子在以下代码中是正确的,我有点麻烦:

 #include<iostream>

struct Foo
{
    Foo(Foo&& other)
    {
        std::cout << "move ctor called";
    }

    Foo(const Foo& other)
    {
        std::cout << "copy ctor called";
    }

    Foo(){}
};

Foo return_foo()
{
    Foo f;
    return f;
}


void main()
{  
    Foo f = return_foo(); // Move ctor is called, but return_foo() is a lvalue ?? 
    std::cin.ignore();    
}

我哪里错了?

4

2 回答 2

4

return_foo() returns a prvalue (because it returns unnamed temporary object). Quote from §3.10/1, emphasis mine:

A prvalue (“pure” rvalue) is an rvalue that is not an xvalue. [ Example: The result of calling a function whose return type is not a reference is a prvalue. The value of a literal such as 12, 7.3e5, or true is also a prvalue. —end example ]

于 2011-07-28T20:33:23.547 回答
2

有一个特殊规则允许将临时值作为右值返回,即以下是等价的 - 明确的“我不再需要这个”版本:

T foo()
{
  T t(a, b, ...); // constructed somehow
  /* ... */
  return std::move(t);
}

int main()
{
  T t = foo(); // we can move-construct this
}

...和隐式版本:

T foo()
{
  T t(a, b, ...);
  /* ... */
  return t;  // implicitly allow moving
}

所有这些都发生返回值优化之后。这意味着在许多情况下,按值返回实际上非常有效。

于 2011-07-28T20:59:24.017 回答