最近有人问我一个关于函数返回值构造的问题。经过一番讨论,我发现事情似乎不太对劲。这是示例:
#include <conio.h>
#include <stdio.h>
#include <iostream>
/*
struct A // Won't be compiled
{
A(void) {};
A(const A &) {};
A(A &&) = delete;
};
*/
struct A // Compiled but...
{
A(void) {};
A(const A &) = delete;
A(A &&) {};
};
A func(void)
{
A temp;
return temp;// 'temp' is a named object, so it should be a lvalue and the A(const A &) should have been invoked.
//return std::move(temp); // OK.
}
int main(void)
{
func();
_getch();
return(0);
}
它将被编译(通过 VC 或 gcc)...但它看起来是错误的。
问题是:即使触发了任何复制推导条件,似乎也没有理由让“A(const A &)”被忽略,不是吗?
最佳答案
12.8 [class.copy]:
32 - When the criteria for elision of a copy operation are met or would be met save for the fact that the source object is a function parameter, and the object to be copied is designated by an lvalue, overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue. [...]
NRVO 允许复制省略,因此 temp
被视为右值。
关于c++ - 编译时似乎错误的代码(关于对象返回),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24207962/