I found a bit of confusion in the ways a variable is constructed, copied, assigned because in the compilers I tried they usually apply some kind of optimization (remove temporary etc.).
I'm listing the different ways I tried and the output of my program in comments below. May be some of them included temporary object creation but are optimized away by the compiler? Please mention if the output is correct as per the standard and if any optimizations were applied.
#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 = type{8}; //ctor
type c5 = type(8); //ctor
type c6 = 8; //ctor
//copy
type ci = c; //copy
type ci2{c}; //copy
type ci3(c); //copy
type ci4 = {c}; //copy
type ci5 = type{c}; //copy
type ci6 = type(c); //copy
//assign
c = c; //assign
c2 = type{8}; //ctor and then assign
c3 = {8}; //ctor and then assign
c4 = type(8); //ctor and then assign
c5 = 8; //ctor and then assign
}
Aucun commentaire:
Enregistrer un commentaire