成员初始值设定项列表的使用如何防止在c++中创建冗余对象
How usage of member initializer list prevents creation of redundant object in c++?
我有一个问题,关于使用和不使用构造函数成员初始值设定项列表初始化对象的区别。
在下面的代码片段中,有两个类Test1
和Test2
,每个类都有两个构造函数,这两个类的对象是在另一个类Example
的默认构造函数中创建的。Test1
的对象是用成员初始值设定项列表中的一个参数创建的,而Test2
的对象是在Example
的构造函数体中用一个参数来创建的。
class Test1 {
public:
Test1() { cout << "Test1 is created with no argument"; }
Test1(int a) { cout << "Test1 is created with 1 argument"; }
};
class Test2 {
public:
Test2() { cout << "Test2 is created with no argument"; }
Test2(int a) { cout << "Test2 is created with 1 argument"; }
};
class Example {
public:
Test1 objTest1;
Test2 objTest2;
Example() : objTest1(Test1(50))
{
objTest2 = Test2(50);
}
};
int main()
{
Example e;
}
上述代码的输出为:
Test1 is created with 1 argument
Test2 is created with no argument
Test2 is created with 1 argument
我的问题
- 为什么
Test2
的对象被创建了两次?(在没有成员初始值设定项的情况下创建的。) Test2
的冗余对象发生了什么?它还占用一些内存吗- 成员初始值设定项列表在初始化类成员变量时是如何工作的
- 使用成员初始值设定项列表是否有任何性能优势?(因为Test1只创建一次)
您的Example
构造函数(隐式)等效于
Example() : objTest1(Test1(50)), objTest2()
{
objTest2 = Test2(50);
}
也就是说,objTest2
对象被隐式地构造和初始化一次(这是由编译器插入的)。
然后,在主体内部显式构造并初始化一个临时Test2
对象,该对象用于将分配给objTest2
。
还要注意,在初始化器列表中,objTest1(Test1(50))
构造一个临时Test1
对象,并将其传递给复制构造函数以初始化objTest1
(尽管大多数编译器应该取消此复制)。您可以将其简化为普通的objTest1(50)
。
相关文章:
- 防止主数据类型C++的隐式转换
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 函数何时会在c++中包含stack_Unwind_Resume调用
- 将指针设置为"nullptr"并不能防止双重删除?
- 如何防止C++遗留代码中的挂起指针
- Python中的for循环与C++有何不同
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 如何防止初始值设定项列表中的错误值?
- OpenCV 我应该使用智能指针来防止内存泄漏吗?
- C++ 防止在映射中放置()时调用析构函数
- 是否可以防止省略聚合初始化成员?
- 在C++中释放内存期间,迭代器与指针有何不同
- 如何在多个线程中创建 QSql数据库连接时防止名称冲突
- 防止在C++中选择错误文件时提升 xml 解析器崩溃
- std::mutex 如何防止线程修改?
- 防止C++中的硬编码数字
- 防止在复制构造函数中隐式调用基构造函数
- 如何防止 CUDA-GDB 中的<优化输出>值
- 防止组合框被关闭
- 按下特定键时快速按此键.如何防止按下扳机键?(C++)