不会调用复制构造函数 [英] Copy Constructor is not invoked

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

问题描述


可能重复:

Possible Duplicate:
Why copy constructor is not called in this case?

考虑下面的示例程序:

#include <iostream>

using namespace std;

class sample
{
    private:
        int x;

    public:
        sample(int a=0) : x(a)
        {
            cout << "default ctor invoked\n";
        }

        sample(const sample& obj)
        {
            cout << "copy ctor invoked\n";
        }

};

int main()
{
    sample s2 = sample(20); //Line1
    sample s3 = 20; //Line2

    return 0;
}

Line1 首先使用参数20调用 sample 类的构造函数显式地。然后,我希望拷贝构造函数被调用初始化s2。

In Line1, first the constructor of sample class is invoked explicitly with the argument 20. Then i expected the copy constructor to be invoked to initialize s2.

在Line2中,首先调用 sample 类的构造函数 implicitly 第一个与参数20.这里也是我期望的副本构造函数被调用来初始化s2。

In Line2, first the constructor of sample class is invoked implicitly first with the argument 20. Here also i expected the copy constructor to be invoked to initialize s2.

在这两种情况下,复制构造函数不被调用?为什么会发生这种情况?我相信,有一些问题我理解的调用的副本构造函数。

In both cases, the copy constructor is not invoked? Why is this happening? I believe, there is something wrong with my understanding of the invocation of copy constructor. Could someone correct me where i am going wrong?

推荐答案

这是预期的。它被称为复制elision

This is expected. It's called copy elision.

您的期望是正确的,但是他们在C ++(性能)中做出了一个例外,它允许编译器将你的表达式当作一个实例的直接初始化,而绕过拷贝构造函数。

Your expectation is correct, but they made an exception in C++ (for performance) which allows the compiler to treat your expression as direct initialization of one instance while bypassing the copy constructor.

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

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