Consider this code, which defines a simple struct Test
(with a default constructor and copy constructor) and returns a std::pair <Test, Test>
from a function.
#include <iostream>
#include <utility>
using namespace std;
struct Test {
Test() {}
Test(const Test &other) {cout << "Test copy constructor called\n";}
};
auto func() {
return make_pair(Test(), Test());
}
int main()
{
auto [a, b] = func(); // Expectation: copies for a and b are both elided
return 0;
}
Surprisingly, the output is
Test copy constructor called
Test copy constructor called
Whereas modifying func
to
auto func() {
return Test();
}
int main()
{
Test a(func());
return 0;
}
Results in the copy constructor not being called. My g++ version is 11.2.0, so I thought that copy elision was guaranteed in this case, but I could be wrong. Could someone confirm if I am misunderstanding RVO?