Is it able to return an object without calling the copy constructor in C++?
In my sample codes, returning an object does not call the copy constructor even though the returned object has same member variable values, and the returning object and l-value of it even have same memory address.
How can is this possible?
Here is the my codes.
#include <iostream>
class foo {
public:
foo(int v) : value{v}
{
std::cout << "default constructor" << std::endl;
}
foo(const foo &v)
{
std::cout << "copy constructor" << std::endl;
this->value = v.value;
}
foo(foo &&v) = delete;
foo &operator=(const foo &v)
{
std::cout << "copy assignment" << std::endl;
if (this == &v) {
return *this;
}
this->value = v.value;
return *this;
}
foo &operator=(foo &&v) = delete;
void print()
{
std::cout << this->value << std::endl;
}
private:
int value = 0;
};
foo func()
{
foo v{10};
std::cout << "returning " << &v << std::endl;
return v;
}
int main()
{
foo v = func();
std::cout << "v is " << &v << std::endl;
v.print();
return 0;
}
And here is the output of the codes.
default constructor
returning 0x7ffeef00e034
v is 0x7ffeef00e034
10
I compiled the codes as follows:
g++ -std=c++17 -Wall -Wextra -g main.cpp