为什么不调用复制构造函数? [英] Why the copy constructor is not called?

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

问题描述

在此代码中:

#include <iostream>

using std::cout;

class Foo {
    public:
        Foo(): egg(0) {}
        Foo(const Foo& other): egg(1) {}

        int egg;
};

Foo bar() {
    Foo baz;
    baz.egg = 3;
    return baz;
}

int main(void) {
    Foo spam(bar());
    cout << spam.egg;
    return 0;
}

输出为 3 ,而我期望它是 1

the output is 3, while I expected it to be 1.

这意味着拷贝构造函数不会在 Foo spam(bar())

That means the copy constructor is not called in the line Foo spam(bar()).

我想这是因为 bar 函数不返回引用。

I guess it's because the bar function doesn't return a reference.

您能否解释在 spam 的初始化时真正发生了什么?

Could you please explain what's really going on at the initialization of spam?

谢谢!

推荐答案

复制/移动elision是所谓的 as-if 规则唯一允许的异常,它通常限制允许编译器对程序执行的转换种类(例如优化) 。

Copy/move elision is the only allowed exception to the so-called "as-if" rule, which normally constrains the kinds of transformations (e.g. optimizations) that a compiler is allowed to perform on a program.

该规则旨在允许编译器执行任何他们想要的优化,只要转换后的程序将工作如果是原来一个。但是,有一个重要的例外。

The rule is intended to allow compilers to perform any optimization they wish as long as the transformed program would work "as if" it was the original one. However, there is one important exception.

C ++ 11标准的第12.8 / 31节:

Per paragraph 12.8/31 of the C++11 Standard:

当满足某些标准时,允许实现省略类
对象的复制/移动构造,即使为复制/移动操作选择的构造函数和/或者对象
的析构函数有副作用
。 [...]在以下情况下允许复制/移动操作(称为复制精确)的删除:(
可以组合以消除多个副本):

When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the constructor selected for the copy/move operation and/or the destructor for the object have side effects. [...] This elision of copy/move operations, called copy elision, is permitted in the following circumstances (which may be combined to eliminate multiple copies):


    <使用与函数返回类型相同的cv非限定
    类型的非易失性自动对象(除了函数或catch子句参数),可以通过将自动对象直接构造为
    来省略复制/移动操作函数的返回值

[...]


  • 当未绑定到引用(12.2)的临时类对象被复制/移动
    到具有相同cv非限定类型的类对象时,可以通过以下方式省略复制/移动操作:
    构造临时对象直接进入省略复制/移动的目标

[...]

换句话说,你不应该依赖于被调用的复制构造函数或move constructor被调用或适用12.8 / 31的规定。

In other words, you should never rely on a copy constructor or move constructor being called or not being called in the cases for which the provisions of 12.8/31 apply.

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

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