开发者

When I initialize a C++ container (such as a std::list) is the copy constructor called?

When I 开发者_如何学Goinitialize a STL container such as a list< vector<char> > using e.g. my_list.push_back(vector<char>(5000, 'T')) is this copied after construction? Or does the compiler invoke the constructor inside list< vector<char> > itself?


In C++03 push_back is defined as void push_back(const T& x);. That means that you are constructing a vector and a const reference to such temporal is being passed to the list. Then the list internally invokes the copy constructor in order to store a copy of such element.

In C++11 there is an extra definition for void push_back(T&& x); that takes an rvalue reference to your temporal vector, and would result in the move constructor being called internally to initialize the copy held by the list.


Compilers are smart. Really smart. In this case, there is an optimization called "copy elision." The C++ standard allows the compiler to omit a copy when a temporary object is used to initialize an object of the same type and the copy constructor of said object has no side effects.

This is in the same class of optimizations as the more popular "as if" rule. That rule allows the compiler to get away with nearly anything it wants, as long as the observable behavior of the resulting program is the same "as if" the standard had been followed exactly.

Here is an example program. On gcc 4.4.5 with both -O0 and -O3 this code results in a "1" being printed. I think that GCC is wrong here... some compilers will output "2" indicating a copy took place. This is where things get tricky in trying to detect behavior that is supposed to be undetectable. In one of those compilers, the only way to tell will be to dive into the resulting assembly.

#include <iostream>

struct elision
{
    explicit elision(int i) : v(i) {
    }

    elision(elision const &copy) : v(copy.v+1) {
    }

    int v;
};

int main()
{
    elision e(elision(1));
    std::cout << e.v << std::endl;
    return 0;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜