Entra

View Full Version : [c++] costruttori di copia


Sabonis
04-11-2008, 15:21
class color{
private:
int r_;
int g_;
int b_;
public:
color(){
cout << "costruttore di default" << endl;
r_ = g_ = b_ = 0;
}

color(int r, int g, int b){
cout << "altro costruttore" << endl;
r_ = r;
g_ = g;
b_ = b;
}

color(const color& c){
cout << "costruttore di copia" << endl;
r_ = c.r_;
g_ = c.g_;
b_ = c.b_;
}

const color& operator=(const color& other){
cout << "operator=" << endl;
if(&other != this){
r_ = other.r_;
g_ = other.g_;
b_ = other.b_;
}
return *this;
}


void print(){
cout << r_ << " "<< g_ << " " << b_ << endl;
}

~color(){
cout << "distruttore" << endl;
}

};


color fun(){
color c(10,0,0);
return c;
}


int main(){
color a = fun();
a.print();
}


Compilando questo programma ottengo questo output:
altro costruttore
10 0 0
distruttore


Come mai? Non dovrebbe eseguire il costruttore di copia per effettuare il return?

tomminno
04-11-2008, 16:29
Compilato in debug o release?
Coś ad occhio direi che il compilatore ha ottimizzato il tuo codice trasformando

color fun()

in

void fun(color & c)

Sabonis
04-11-2008, 16:56
Ho provato a compilare con nessuna ottimizzazione:
g++ -O0 -o prova -g main.cpp

o anche in modalità debug ma il comportamento rimane lo stesso.

tomminno
05-11-2008, 07:53
Ho provato a compilare con nessuna ottimizzazione:
g++ -O0 -o prova -g main.cpp

o anche in modalità debug ma il comportamento rimane lo stesso.

E' una ottimizzazione del compilatore. Magari la applica anche senza ottimizzazione e in debug.
Ad esempio VS2008 in debug dà:

altro costruttore
costruttore di copia
distruttore
10 0 0
distruttore

In release invece:

altro costruttore
10 0 0
distruttore