Initialization via ctor vs. initialization via assignment

M

Matthias Kaeppler

Hi,

say I have an arbitrary class Bar:

1 Bar a;
2 Bar b(a);
3 Bar c = a;

In line 3, is the default ctor called for c _first_ and _then_ the
assignment operator, or is c never default constructed and immediately
initialized with a?

My point is, for complex objects, is it likely that initialization via
assignment is less efficient than via constructor calls? What is the
recommended approach?
 
G

Gianni Mariani

Matthias said:
Hi,

say I have an arbitrary class Bar:

1 Bar a;
2 Bar b(a);
3 Bar c = a;

In line 3, is the default ctor called for c _first_ and _then_ the
assignment operator, or is c never default constructed and immediately
initialized with a?

My point is, for complex objects, is it likely that initialization via
assignment is less efficient than via constructor calls? What is the
recommended approach?

2 & 3 mean exactly the same thing. BTW, one way of answering this
questing is by writing a 30 liner like so.

#include <iostream>
#include <ostream>

struct A
{
A()
{
std::cout << "A default\n";
}

A( const A & )
{
std::cout << "A copy\n";
}

A & operator= ( const A & )
{
std::cout << "A operator =\n";
return * this;
}

};


int main()
{
std::cout << "A x;\n";
A x;

std::cout << "A y( x );\n";
A y( x );

std::cout << "A z = x;\n";
A z = x;
}
 
V

Victor Bazarov

Matthias said:
say I have an arbitrary class Bar:

1 Bar a;
2 Bar b(a);
3 Bar c = a;

In line 3, is the default ctor called for c _first_ and _then_ the
assignment operator,
No.

> or is c never default constructed and immediately
initialized with a?

'c' is constructed from 'a' via the copy c-tor. Since 'a' and 'c' are
of the same type, the case 3 is the same as the case 2.
My point is, for complex objects, is it likely that initialization via
assignment is less efficient than via constructor calls? What is the
recommended approach?

There is no assignment involved in construction (unless you make it so).

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top