请问我是否正确,对函数返回值使用 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/