编译错误的代码(关于对象返回)

A code which seems wrong being compiled (about object return)

本文关键字:返回 对象 于对象 错误 代码 编译      更新时间:2023-10-16

最近有人问我一个关于构造函数返回值的问题。经过几次讨论,我发现有些事情似乎不太对。示例如下:

#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被视为右值。