Benefits of Initialization lists
Solution 1:
The second version is calling string's default ctor and then string's copy-assignment operator -- there could definitely be (minor) efficiency losses compared to the first one, which directly calls c's copy-ctor (e.g., depending on string's implementation, there might be useless allocation-then-release of some tiny structure). Why not just always use the right way?-)
Solution 2:
I think the only way to initialize const data members is in the initialization list
Eg. in the header:
class C
{
C();
private:
const int x;
int y;
}
And the in the cpp file:
C::C() :
x( 10 ),
y( 10 )
{
x = 20; // fails
y = 20;
}
Solution 3:
It's a great way to initialize members that :
- are const
- don't have a default constructor (it's private)
Solution 4:
Remember that there is a distinct difference between a copy constructor and an assignment operator:
- the copy ctor constructs a new object using some other instance as a place to get initialization information from.
- the assignment operator modifies an already existing object that has already been fully constructed (even if it's only by using a default constructor)
So in your second example, some work has already been done to create name
by the time that
name=n;
is reached.
However, it's quite possible (especially in this simple example) that the work done is vanishingly small (probably just zeroing out some data members in the string
object) and that the work is optimized away altogether in an optimized build. but it's still considered good form to use initializer lists whenever possible.