在下面的代码中调用哪个构造函数?

在下面的代码中调用哪个构造函数?

问题描述:

请查看以下代码:

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.