开发者

Does a std::vector constructor not call object constructors for each element?

My code resembles somethin开发者_运维技巧g along these lines.

class A
{
  public:
    A(int i) { printf("hello %d\n", i); }
    ~A() { printf("Goodbye\n"); }
}


std::vector(10, A(10));

I notice that hello prints out once. It seems to imply that the vector only allocates space for the element but doesn't construct it. How do I make it construct 10 A objects?


The object is constructed only once, as you pass it to std::vector. Then this object is copied 10 times. You have to do a printf in the copy constructor to see it.


You forgot the copy constructor:

#include <iostream>
#include <vector>
using namespace std;

class A
{
        int i;
public:
        A(int d) : i(d) { cout << "create i=" << i << endl; }
        ~A() { cout << "destroy" << endl; }
        A(const A& d) : i(d.i) { cout << "copy i=" << d.i << endl; }
};

int main()
{
        vector<A> d(10,A(10));
}

Output:

create i=10
copy i=10
copy i=10
copy i=10
copy i=10
copy i=10
copy i=10
copy i=10
copy i=10
copy i=10
copy i=10
destroy
destroy
destroy
destroy
destroy
destroy
destroy
destroy
destroy
destroy
destroy


A(10) constructs a temporary object. Only once. The 10 elements of your vector are constructed via the copy-constructor. So if you define a copy-constructor to print B you'll get 10 B's.


Define copy constructor and you will be fine:

#include <cstdio>
#include <vector>


class A
{
    public:
        A(int i) { printf("hello %d\n", i); }
        ~A() { printf("Goodbye\n"); }
        A(const A&)
        {
            printf("copy constructing\n");
        }
};


int main()
{
    std::vector< A > a( 10, A(5) );
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜