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()
的默认构造函数,然后调用复制构造函数(理论上,复制受复制省略约束).此处不进行任何分配.
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++ 对象实例化与赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 对象实例化与赋值


基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01