Constructors

I got other output from what i expected:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>

class Foo
{
public:
	int data0;
	int data1;

	Foo(int d0, int d1) : data0(d0), data1(d1)
	{
		std::cout << "Foo(int,int)" << std::endl;
	}
	Foo(const Foo& o) : data0(o.data0), data1(o.data1)
	{
		std::cout << "Foo(const Foo&)" << std::endl;
	}
};

int main()
{
	Foo f(Foo(5, 7));

	std::cout << "Press enter to exit...";
	std::cin.get();
	return 0;
}


output:

Foo(int,int)


expected output:

Foo(int,int)
Foo(const Foo&)

???
Last edited on
I would guess that the compiler optimized away the temporary created by the inner call to the constructor.
I think that the compiler is optimizing the statement
Foo f(Foo(5,7))
to
Foo f(5,7)

In this case if you can dump the assembly code, you might find that no temporary object is generated at all.

Indeed, this is a type of copy elision explicitly allowed by the C++ standard, similar to NRVO.
Ok, thanks. This is the first time i heard of this.
In what circumstances this won't work? I want to know when i can rely on this feature.
There are compiler options to disable the copy elision, once you do that then you can be pretty sure about your code. For g++ we have this option "-fno-elide-constructors".
Topic archived. No new replies allowed.