c++ - auto 与 auto&& 函数返回值

标签 c++ function c++11 return-value auto

请问我是否正确,对函数返回值使用 auto&& 总是比使用 auto 更好。例如,在

auto val = someObj.getVal();

如果 getVal() 返回引用,则 val 将是一个拷贝。但是,使用通用引用 auto&& 没有这样的缺点吗?我唯一需要知道的信息是 getVal() 是否为 const。

最佳答案

However, use of the universal reference auto&& does not have such a disadvantage?

不,它不会复制返回值。

问题

但是,有时复制是必要的,并且对 prvalue 和引用使用 auto&& 会创建悬挂引用。考虑这种情况:

struct A {
    // A: Another programmer changed it from:
    // int getVal() { return mInteger; }

    // B
    int &getVal() { return mInteger; }

private:
    int mInteger;
};

int main() {
    A *a = new A;

    auto   integerCopy = a->getVal();

    // int& on case B, int&& on case A.
    auto&& integerRvalueRef  = a->getVal();

    delete a;

    // Ok, no matter what getVal returns.
    std::cout << integerCopy;
    // Dangling Reference dereference if getVal returns a reference. 
    std::cout << integerRvalueRef;
}

如您所见,使用 auto,更改此返回值没有问题。但是,对于 auto&&,它创建了一个悬挂引用。

结论

像常规引用一样使用auto&&:谨慎对待它。将它用于 prvalue 和引用值返回值可能会导致意外情况。

关于c++ - auto 与 auto&& 函数返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40338200/

相关文章:

c++ - C++中BYTE数组的长度

c++ - 循环无法正常工作

function - 动态调用功能

c++ - 在 C++ 中运行时生成函数指针声明?

c++ - 在 C++ 中使用 erase-remove 习语时,我应该通过引用传递吗?

c++ - 尝试在基类之外创建派生类的实例时出错

C++ 该代码 fstream 有什么问题

python - Python按顺序运行函数;如果失败,请停止

java - 正则表达式减少函数参数之间的空格

c++ - 如何从重载解析中删除函数?