Why is copy constructor called only twice here (should be thrice?)

T

TechCrazy

I am compiling like

g++ -O0 MyString.cpp

Should the copy cnstrs be called thrice? Any optimization going on
here?

--------------------------
#include <iostream>
#include <string>
using namespace std;
class MyString: public string {
public:
MyString(const char * str): string(str) {
cout << "copy ctr 1 called" << endl;
}
MyString(MyString const & str): string(str) {
cout << "copy ctr 2 called" << endl;
}
};

MyString getString() {
MyString x("rrr"); //copy ctr 1 called

//This should call copy ctr once to create the temporary
//that will be returned
return x;
}

int main() {
//This should call copy ctr again with the temporary
//created at the end of getString() to create y
MyString y (getString());
}
 
B

benben

TechCrazy said:
I am compiling like

g++ -O0 MyString.cpp

Should the copy cnstrs be called thrice? Any optimization going on
here?

The getString() function is eligible for Named Return Value (NRV)
optimization, which eliminates the temporary.

Regards,
Ben
 
I

Ian

TechCrazy said:
I am compiling like

g++ -O0 MyString.cpp

Should the copy cnstrs be called thrice? Any optimization going on
here?
Yes, the object returned by getString is y.
--------------------------
#include <iostream>
#include <string>
using namespace std;
class MyString: public string {
public:
MyString(const char * str): string(str) {
cout << "copy ctr 1 called" << endl;
}
Not a copy constructor.

Ian
 
B

benben

Ian, I think the OP wants to ask why the constructor was called twice than
three times.

ben
 
K

Karl Heinz Buchegger

TechCrazy said:
But, I turned off all optimization with -O0

Then ask the guys writing your compiler, why NRVO is still
done in that case.

I guess the answer will be something like: NRVO is always on, because
it is an optimization which affects the callee as well as the caller.
If we would allow to disable it, then there could be a situation, where
the caller is compiled for NRVO, while the callee is not. And that will
give you a big crash.
 

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

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top