Why is the output foo3
equal to 3
?
i would suggest, when bar(foo1)
is called, the function bar
creates a copy of foo1
on the stack, so it's value is equal to 0, when this value is returned, the copy-constructor for foo3
increments the value again so it should be 2?
Thanks in advance.
this is my code:
#include <iostream>
struct Foo {
Foo()
: x(0)
{
}
Foo(const Foo& foo)
: x(foo.x + 1)
{
}
int x;
};
Foo bar(Foo foo)
{
foo.x++;
return foo;
}
int main()
{
Foo foo1;
Foo foo2 = foo1;
std::cout << "A:" << foo1.x << std::endl;
std::cout << "B:" << foo2.x << std::endl;
Foo foo3 = bar(foo1);
std::cout << "C:" << foo3.x << std::endl;
}
output:
A:0
B:1
C:3
I believe there are three copy constructors at work here, the line foo2 = foo1
, the passing of foo1
into bar
, and the returning of foo1
from bar
.
Modifying your code makes it clear what is happening:
#include <iostream>
struct Foo {
Foo()
: x(0)
{
std::cout << "Constructor called" << std::endl;
}
Foo(const Foo& foo)
: x(foo.x + 1)
{
std::cout << "Copy constructor called" << std::endl;
}
int x;
};
Foo bar(Foo foo)
{
std::cout << "B2:" << foo.x << std::endl;
foo.x++;
return foo;
}
int main()
{
Foo foo1;
Foo foo2 = foo1;
std::cout << "A:" << foo1.x << std::endl;
std::cout << "B:" << foo2.x << std::endl;
Foo foo3 = bar(foo1);
std::cout << "C:" << foo3.x << std::endl;
}
Output:
Constructor called
Copy constructor called
A:0
B:1
Copy constructor called
B2:1
Copy constructor called
C:3