'Why is copy constructor preferred over assignment operator when initializing a class's member variable? [duplicate]
If we have:
public:
MyClass(const std::string& my_str);
private:
std::string _myStr
In the implementation:
MyClass::MyClass(const std::string& my_str):
_mystr(my_str)
vs
MyClass::MyClass(const std::string& my_str){
_mystr = my_str
}
Why is the first version preferred over second?
Solution 1:[1]
Why is the first version preferred over second?
The first version initializes the data member while the second version assignes a value to it.
The second version has an overhead because, in the second case the data member _mystr will first be default initialized before the body of the constructor is entered and then inside the body of the ctor it will be assigned a value(using _mystr = my_str). So in the second case there are 2 steps involved:
_mystrwill be default initialized before the body of the ctor is entered.Next, inside the body of the ctor , the assignment
_mystr = my_strwill happen.
Note that initialization and assignment are different things in C++.
Version 1
//-------------------------------------------vvvvvvvvvvvvv--->INITIALIZATION of data member myStr
MyClass::MyClass(const std::string& my_str): myStr(my_str)
{
//no ASSIGNMENT happening here
}
Version 2
MyClass::MyClass(const std::string& my_str)//before the body of this ctor is entered, myStr will be default initialized
{
myStr = my_str; //ASSIGNMENT happening here
}
Also, take a look at What are the rules about using an underscore in a C++ identifier?.
Solution 2:[2]
Using a copy constructor expresses your intent more clearly. If you did an assignment instead (in the body of the constructor, not the initialization list) you'd be initializing the member twice, once to its default value and then finally to the value you wanted it to have.
For some members, such as references, you really don't have a choice.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Mark Ransom |
