c++ - 编译时似乎错误的代码(关于对象返回)

标签 c++ return-value-optimization

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

#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/

相关文章:

c++ - 隐式转换 : is the following warning valid?

c++ - 按值返回时强制 RVO/移动构造

c++ - 复制省略和返回值优化与复制构造函数

c++ - 运算符重载的私有(private)函数

c++ - 从开发人员的角度看 Linux 文件夹结构

c++ - RVO, move 语义和优化代码的斗争

c++ - 为什么 std::move 会阻止 RVO(返回值优化)?

c++ - HashMap 以找到添加到给定总和的一对

C++关键部分不起作用