c++ - C++:如果没有对这些不同的创建/初始化、复制、分配方式进行优化,输出是什么?
问题描述
我发现变量的构造、复制、分配方式有些混乱,因为在我尝试过的编译器中,它们通常会应用某种优化(删除临时等)。
我在下面的评论中列出了我尝试过的不同方式以及我的程序的输出。可能其中一些包括临时对象创建但被编译器优化掉了?请说明输出是否按照标准正确,如果没有应用优化,输出是什么。
#include <iostream>
using namespace std;
class type {
public:
type(int z){cout << "ctor"<<endl;};
type(const type&){cout<<"copy"<<endl;}
void operator=(const type& ){cout <<"assign"<<endl;}
};
int main()
{
//constructor
type c(8); //ctor
type c2{8}; //ctor
type c3 = 8; //ctor
type c4 = {8}; //ctor
type c5 = type(8); //ctor
type c6 = type{8}; //ctor
cout <<endl;
//copy
type ci0(c); //copy
type ci1{c}; //copy
type ci2 = c; //copy
type ci3 = {c}; //copy
type ci4 = type(c); //copy
type ci5 = type{c}; //copy
cout <<endl;
//assign
c2 = c; //assign
c2 = {c}; //assign
c2 = type{c}; //copy and then assign
c2 = type(c); //copy and then assign
c2 = 8; //ctor and then assign
c2 = {8}; //ctor and then assign
c2 = type(8); //ctor and then assign
c2 = type{8}; //ctor and then assign
}
解决方案
使用显式到 ctor 和复制 ctor 并删除每个函数,我能够得到以下结果。
//constructor
type c(8); //explicit ctor
type c2{8}; //explicit ctor
type c3 = 8; //implicit ctor, explicit copy
type c4 = {8}; //implicit ctor
type c5 = type(8); //explicit ctor, implicit copy
type c6 = type{8}; //explicit ctor, implicit copy
cout <<endl;
//copy
type ci0(c); //explicit copy
type ci1{c}; //explicit copy
type ci2 = c; //implicit copy
type ci3 = {c}; //implicit copy
type ci4 = type(c); //implicit copy
type ci5 = type{c}; //implicit copy
cout <<endl;
//assign
c2 = c; //assign
c2 = {c}; //assign
c2 = type{c}; //implicit copy and then assign
c2 = type(c); //implicit copy and then assign
c2 = 8; //implicit ctor and then assign
c2 = {8}; //implicit ctor and then assign
c2 = type(8); //explicit ctor and then assign
c2 = type{8}; //explicit ctor and then assign
推荐阅读
- javascript - 方法中相同的BMI
- liquibase - Liquibase force 始终运行
- vb6 - 从 RTSP 流中保存和图像 (VB6)
- firebase - 在 Firebase 上存储数据以供稍后查询
- c# - 尝试发布数据但不断收到 HTTP 错误 404
- android - Android SharedPrefences 一个键的多个值
- graphql - 如何迁移现有存储过程以使用 graphql
- hyperledger-fabric - 从织物样本构建平衡转移时,签名集不满足策略 /Channel/Application/Org1/Admins
- python - 如何将x轴列为国家而不是python中的数字
- java - EnableGlobalMethodSecurity 注释中的运行时条件 prePostEnable