Kindly consider the following program
#include <iostream>
#include <vector>
using namespace std;
//class whose object gets store in vector
template <typename T>
class X
{
T data;
public:
X(){ cout << "Object " << this << " Default Ctor\n";}
X(T inData) : data(inData){ cout << "Object " << this << " Parameterized Ctor\n";}
X(const X &x) : data(x.data){ cout << "Object " << this << " Copy Ctor\n";}
X(X &&x) : data(move(x.data)){ cout << "Object " << this << " Move Ctor\n";}
~X(){ cout << "Object " << this << " Distructor\n";}
friend ostream & operator << (ostream & strm, X & x) { return strm << x.data;}
};
//helper print function
template <typename T>
ostream& operator << (ostream & strm, vector<T> & v) {
int i=0;
strm << "vector data -> [";
for (auto & ele : v )
strm << ele << ((++i < v.size())?",":"");
return strm << "]\n";
}
int main()
{
vector<X<int>> v = { 1, 2 };
cout << v;
}
Run output (compiler gcc 5.1.0)
Object 0x28fe94 Parameterized Ctor
Object 0x28fe98 Parameterized Ctor
Object 0x3b7800 Copy Ctor
Object 0x3b7804 Copy Ctor
Object 0x28fe98 Distructor
Object 0x28fe94 Distructor
vector data -> [1,2]
Object 0x3b7800 Distructor
Object 0x3b7804 Distructor
It is "impossible", by any means, to access object's 0x28fe98 and 0x28fe94 that were temporarily created and copied into vector.
Why can't C++ std mention that when initializing a container using initializer list then the object created temporarily should be moved and not copied ?
Why can't C++ std mention that when initializing a container using initializer list then the object created temporarily should be moved and not copied ?