首页 > 解决方案 > 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
}

标签: c++c++11constructorcopy-constructorcopy-assignment

解决方案


使用显式到 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

推荐阅读