编译错误的代码(关于对象返回)
A code which seems wrong being compiled (about object return)
最近有人问我一个关于构造函数返回值的问题。经过几次讨论,我发现有些事情似乎不太对。示例如下:
#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 -除了源对象是函数形参,且要复制的对象由左值指定外,如果满足或将满足省略复制操作的条件,则首先执行选择复制构造函数的重载解析,就像对象由右值指定一样。[…]
NRVO允许复制省略,因此temp
被视为右值。
相关文章:
- 如何返回对象C++的数组
- 如何使用std::min和std::less返回对象
- 如何通过引用返回对象
- 如何安全地从 DLL 调用返回对象
- 如何在不销毁对象的情况下返回对象列表
- 什么更好?返回对象指针列表?或返回指向对象列表的指针?
- 使用返回对象的函数处理错误
- 何时返回指针与返回对象的一般经验法则?
- 如何使用运算符+重载函数正确返回对象?
- C++,class,一个返回对象的函数
- 运算符的返回对象 = C++ 中的重载
- 从队列返回对象的最快方法,但前提是队列有它
- 如何使用条件表达式返回对象指针?
- 使用构造函数从函数返回对象
- 隐式转换函数的返回对象时是否会影响性能?
- 返回对象时从'const DList<int>* const'到 'DList<int>*' [-fallowive] 的转换无效
- 按值和堆栈大小限制返回对象
- 我应该如何从函数返回对象?
- c++:何时传递指针与返回对象
- 返回对象会丢失属性