By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,479 Members | 1,729 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,479 IT Pros & Developers. It's quick & easy.

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

P: n/a
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());
}

------------
This program is printing:

copy ctr 1 called
copy ctr 2 called

Jul 23 '05 #1
Share this Question
Share on Google+
5 Replies


P: n/a

"TechCrazy" <Te*******@hotpop.com> wrote in message
news:11*********************@g43g2000cwa.googlegro ups.com...
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
Jul 23 '05 #2

P: n/a
But, I turned off all optimization with -O0

Jul 23 '05 #3

P: n/a
Ian
TechCrazy wrote:
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
Jul 23 '05 #4

P: n/a
Ian, I think the OP wants to ask why the constructor was called twice than
three times.

ben
Jul 23 '05 #5

P: n/a
TechCrazy wrote:

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.

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 23 '05 #6

This discussion thread is closed

Replies have been disabled for this discussion.