为什么在返回LOCAL变量时不调用复制构造函数 [英] Why isn't the copy-constructor called when returning LOCAL variable

查看:200
本文介绍了为什么在返回LOCAL变量时不调用复制构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么当我尝试返回一个局部变量定义在一个函数中时,不会调用复制构造函数。请参阅以下简化示例:

I can't figure out why the copy-constructor is not called when I try to return a local variable defined within a function. See the following simplified example:

#include <iostream>
using namespace std;

class X {
public:
    X() { cout << "Default Constructor" << endl; }
    X(const X&) { cout << "Copy Constructor" << endl; }
};

X f(X x) { return x; }

X g() { 
    X y;
    return y;
}

int main() {
    cout << "First create an object" << endl;
    X a;
    cout << "Call f()" << endl;
    f(a);
    cout << "Call g()" << endl;
    g();
}

编译程序的输出如下

First create an object
Default Constructor
Call f()
Copy Constructor
Copy Constructor
Call g()
Default Constructor



我理解调用<$ c时发生了什么$ c> f(),但不知道为什么 g()的调用中返回y c $ c>不会触发复制构造函数。

I understand what's going on when calling f(), but have no idea why return y inside the call of g() does not trigger the copy-constructor.

推荐答案

编译器优化了返回副本。这被称为NRVO(命名返回值优化)。

The compiler optimizes away the return copy. This is known as NRVO (Named Return Value Optimization).


在具有类返回类型的函数中的返回语句中,当表达式是具有与函数返回类型相同的cv非限定类型的非易失性自动对象(除了函数或catch子句参数之外)的名称,可以通过将自动对象直接构造为函数的返回值

in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object (other than a function or catch-clause parameter) with the same cv-unqualified type as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function’s return value

编译器允许这样做,即使拷贝构造函数有副作用。

The compiler is allowed to do this, even if the copy constructor has side effects.


当满足某些条件时,允许实现忽略类对象的复制/移动构造,即使复制/移动构造函数和/对象有副作用。

When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the copy/move constructor and/or destructor for the object have side effects.

也就是说,如果你给你的复制/移动构造函数副作用,你的程序有多个有效的执行路径,具体取决于您的编译器是否要优化。

That is, if you give your copy/move constructors side effects, your program has multiple valid execution paths, depending on whether your compiler wants to optimize or not.

这篇关于为什么在返回LOCAL变量时不调用复制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆