mercredi 29 juillet 2020

Can modern C++ compilers optimise the assignment operator for temporary variables?

Below is MyStruct class implementation which has default and copy constructors.

struct MyStruct {
    MyStruct(const string& name) {
        cout << "Default constructor called" << endl;
        name_ = name;
    }
    MyStruct(const MyStruct& S) {
        cout << "Copy constructor called" << endl;
        name_ = S.name_;
    }
    string name_;
}

Creating an object in the following way: MyStruct S = MyStruct("Hello"); calls a default constructor with "Hello" argument. I suspect my compiler (gcc version 7.5.0) does the optimisation by avoiding to create a temporary MyStruct("Hello") object.

However, the compiler does not optimize the analogous case for assignment operators:

MyStruct& operator=(const string& name) { // First assignment operator
    name_ = name;
    return *this;
}
MyStruct& operator=(const MyStruct& S) { // Second assignment operator
    name_ = S.name_;
    return *this;
}

Reassigning S to another struct:

MyStruct S = MyStruct("Hello"); // initial construction
S = MyStruct("world"); // reassignment

calls a constructor for the second time to construct the temporary MyStruct("world") object. After that, the second assignment operator is called.

Question:

  • is there a way to modify the code such that the call to the first assignment operator with an argument "world" would be called?

  • Is the first optimisation part of the modern C++ standard (i.e. will work with all compilers), or only works with specific compilers?

Aucun commentaire:

Enregistrer un commentaire