在下面的代码中调用哪个构造函数? [英] Which constructor is called in the following code?

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

问题描述

请查看以下代码:

class Test
{
public:
    Test()
    {
        cout << "default\n";
    }

    Test(const Test&)
    {
        cout << "copy\n";
    }

    Test& operator = (const Test&)
    {
        cout << "assign\n";
        return *this;
    }
};

int main()
{
    Test t = Test();
}

在main函数中应该调用哪个构造函数?

Which constructor should be called in the main function?

我运行,它打印默认,没有别的。但是,如果我使复制构造函数和赋值运算符私有,它不编译。但是它没有以任何方式使用该构造函数。

I run and it prints "default" and nothing else. However, if I make the copy constructor and assignment operator private, it doesn't compile. But it wasn't using that constructor any way.

应该使用哪个构造函数?是标准保证吗?这是我不知道的一些规则吗?

Which constructor should be used? Is it guaranteed by standard? Is this some rule I didn't know about?

活代码示例:

http://ideone.com/lnUEA1

http://ideone.com/nXjAo4

推荐答案

编译器可以自由优化不必要的副本。

Compilers are free to optimize out unnecessary copies. That doesn't mean an accessible copy constructor isn't needed.

您的代码显示复制初始化,这意味着复制构造函数必须可用。理论上,将调用默认和复制构造函数。

Your code show copy initialization, which means a copy constructor must be available. Theoretically, the default and copy constructor would be called.

不需要或不使用赋值运算符。

The assignment operator isn't needed or used.

这篇关于在下面的代码中调用哪个构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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