C ++对象实例化与赋值 [英] C++ Object Instantiation vs Assignment
本文介绍了C ++对象实例化与赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这之间有什么区别:
TestClass t;
并且:
TestClass t = TestClass();
我预计第二个可能会调用构造函数两次,然后调用operator =,而是调用构造函数正确一次,就像第一个。
I expected that the second might call the constructor twice and then operator=, but instead it calls the constructor exactly once, just like the first.
推荐答案
TestClass t;
调用默认构造函数。
TestClass t = TestClass();
是复制初始化。它将调用 TestClass()
的默认构造函数,然后调用复制构造函数(理论上,复制受限于 copy elision )。 此处没有分配。
is a copy initialization. It will call the default constructor for TestClass()
and then the copy constructor (theoretically, copying is subject to copy elision). No assignment takes place here.
还有直接初始化的概念:
TestClass t(TestClass());
如果要使用赋值运算符:
If you want to use the assignment operator:
TestClass t;
TestClass s;
t = s;
这篇关于C ++对象实例化与赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文