Why isn't copy constructor called?

Hi there.

I've this class member function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
MyClass(const MyClass& copy) { cout << "copy ctor"; }
MyClass(MyClass&& move) { cout << "move ctor"; }

static MyClass test()
{
   if(1<0)
    return MyClass();
   else
    return MyClass();
}

// ... ... ...
 
int main()
{
   MyClass my ( MyClass::test() );
}


The output is null here. There's no output. There was a copy elision here.

But it's strange, I read somewhere that copy elision DOES NOT OCCUR when there are more than 1 return statements in one function... which is in THIS CASE.

But copy elision occurs the same. Why?

The rules on copy elision say nothing about multiple return statements.
That doesn't say anything about copy elision being forbidden if there is more than one return statement, and it appears that you wrote that answer yourself anyway.
Last edited on
If you see here in the second answer -> http://stackoverflow.com/questions/12953127/what-are-copy-elision-and-return-value-optimization

at the end:


Common limitations of copy elision are:

multiple return points
conditional initialization
That is discussing the limitations of a specific compiler. Are you using Microsoft's Visual C++ compiler, from Visual Studio 2005? That's what has that limitation.

Perhaps you would care to check the actual C++ rules for copy elison: http://en.cppreference.com/w/cpp/language/copy_elision

Copy elision is not forbidden just because there are multiple return paths.
Last edited on
I don't, but if you see my post here http://stackoverflow.com/questions/35506708/move-constructor-vs-copy-elision-which-one-gets-called (the question is self-answered)

There I have a if-else statement before the return, and the move was performed.

In the other case, I didn't have if-else, just a plain return... and copy elision was performed.

NOW, copy elision applies even when I have an if-else
So what?

Your question was "How come it does copy elision when there's more than one return statement?"

Clearly, you thought that having more than one return statement meant that copy elision was forbidden. It isn't.

You throwing up examples of times when it is and isn't used is irrelevant.
Again, in that question there are 2 examples. In one move constructor gets called, in the other copy elision is performed.

From what depends this?
So is this a different question now?

Is the question no longer: "How come it does copy elision when there's more than one return statement?"
You said it doesn't depend from the number of return stats. Okay, so from what?
It depends on what the compiler can or chose to do.
Last edited on
Topic archived. No new replies allowed.