Efficiency of vector initialization using initializer list

41 views
Skip to first unread message

Amit Mishra

unread,
Aug 11, 2017, 8:00:40 AM8/11/17
to ISO C++ Standard - Discussion

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 ?

Nicol Bolas

unread,
Aug 11, 2017, 10:58:42 AM8/11/17
to ISO C++ Standard - Discussion
On Friday, August 11, 2017 at 8:00:40 AM UTC-4, Amit Mishra wrote:

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 ?


Because those objects were created as a `const` array, and you cannot move from a `const` object.
Reply all
Reply to author
Forward
0 new messages