复制构造函数elision? [英] Copy constructor elision?

查看:177
本文介绍了复制构造函数elision?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

给定下面的代码,我无法理解gcc中的输出。我期望两个对象被创建和销毁,而是看到只有一个调用构造函数和析构函数。这里发生了什么?

Given the code below, I fail to understand the output in gcc. I expect two objects to be created and destroyed but instead see only one call to the constructor and the destructor. What's happening here?

#include <string>
#include <iostream>

struct Huge{
        Huge() { std::cout << "Constructor" << std::endl; }
        Huge(Huge const &r) { std::cout << "Copy Constructor" << std::endl; }
        ~Huge() { std::cout << "Destructor" << std::endl; }
};

Huge g() {
        std::cout << "Entering g" << std::endl;
        Huge temp;
        std::cout << "Exiting g" << std::endl;
        return temp;
}

int main(){
        Huge h2(g());
        std::cout << "Before leaving main" << std::endl;
}

这个代码在g ++(4.4)中的输出是

The output of this code in g++ (4.4) is


输入g

Entering g

构造函数

退出g

离开主之前

解构函数


推荐答案

是的,这是通过 命名返回值优化

Yes this is copy elision through Named Return Value Optimization.

C ++标准允许实现省略由return语句产生的复制操作,即使复制构造函数有副作用。

The C++ standard allows an implementation to omit a copy operation resulting from a return statement, even if the copy constructor has side effects.

参考:

C ++ 03标准:

12.8复制类对象:

#15


当满足某些标准时,即使对象的复制构造函数和/或析构函数有副作用,也允许实现忽略类对象的复制构造。 在这种情况下,实现将忽略复制操作的源和目标视为两种不同的引用同一对象的方式,并且该对象的销毁发生在两个对象将会没有优化即被销毁 .111)在以下情况下可以在
中允许复制操作的检测(可以组合以消除多个副本):

When certain criteria are met, an implementation is allowed to omit the copy construction of a class object, even if the copy constructor and/or destructor for the object have side effects. In such cases, the implementation treats the source and target of the omitted copy operation as simply two different ways of referring to the same object, and the destruction of that object occurs at the later of the times when the two objects would have been destroyed without the optimization.111) This elision of copy operations is permitted in the following circumstances (which may be combined to eliminate multiple copies):

- 在具有类返回类型的函数的返回语句中,当表达式是具有与函数返回类型相同的cv非限定类型的非易失性自动对象的名称时,可以通过直接将自动对象构造成函数的返回值

— in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object with the same cv-unqualified type as the function return type, the copy operation can be omitted by constructing the automatic object directly into the function’s return value

- 当未绑定到引用(12.2)的临时类对象将被复制到类对象时相同的cv非限定类型,通过将临时对象直接构造为省略复制的目标,可以省略复制操作

— when a temporary class object that has not been bound to a reference (12.2) would be copied to a class object with the same cv-unqualified type, the copy operation can be omitted by constructing the temporary object directly into the target of the omitted copy

这篇关于复制构造函数elision?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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