CPP Refs states:
— when a temporary class object that has not been bound to a reference (12.2) would be copied/moved to a class object with the same cv-unqualified type, the copy/move operation can be omitted by constructing the temporary object directly into the target of the omitted copy/move
Let's say I have some test code:
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
class MyVector : public vector<T>
{
public:
MyVector()
{
cout << "MyVector()" << endl;
}
MyVector(const MyVector& right):
vector<T>(right)
{
cout << "MyVector(const MV&)" << endl;
}
MyVector(MyVector&& right) :
vector<T>(right)
{
cout << "MyVector(MV&&)" << endl;
}
};
class A
{
public:
A() = default;
A(MyVector<char> vec) :
_vec(std::move(vec))
{
cout << "A(MyVec)" << endl;
}
private:
MyVector<char> _vec;
};
MyVector<char> funcElision()
{
cout << "\nElision" << endl;
MyVector<char> tmp;
tmp.emplace_back('a');
return tmp;
}
A funcElisionExternal()
{
cout << "\nElision external test" << endl;
return A(funcElision());
}
A funcElisionInternal()
{
cout << "Elision internal test" << endl;
MyVector<char> tmp;
tmp.emplace_back('a');
return A(tmp);
}
int main()
{
auto a = funcElisionInternal();
auto b = funcElisionExternal();
}
The output of the test is:
Elision internal test
MyVector()
MyVector(const MV&)
MyVector(MV&&)
A(MyVec)
Elision external test
Elision
MyVector()
MyVector(MV&&)
A(MyVec)
End
The function elisionExternal does work as expected, but i don't know why the elisionInternal is doing the copy operation, since the MyVec is temporary object?