2010-11-09 51 views
4

我的代码类似于沿着这些线的东西。std :: vector构造函数是否不为每个元素调用对象构造函数?

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


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

我注意到hello打印出来一次。 它似乎暗示该向量仅为元素 分配空间,但不构成它。我如何使它构建10个对象?

+1

不少人看不惯用C风格IO中的C代码(http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.1) – Flexo 2010-11-09 11:23:52

+0

它只是一个前足够好吗? – Matt 2010-11-09 11:35:57

回答

12

当您将它传递给std :: vector时,该对象只构造一次。然后这个对象被复制10次。您必须在复制构造函数中执行printf才能看到它。

+0

谢谢你解释它。 – Matt 2010-11-09 11:43:09

3

A(10)构造一个临时对象。只有一次。您的载体的10个元素通过复制构造函数构建。所以,如果你定义一个拷贝构造函数来打印B,你将得到10个B。

1

定义拷贝构造函数,你将被罚款:

#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)); 
} 
+1

为什么#include 但不使用它们,不包括? – Flexo 2010-11-09 11:20:09

+0

@awoodland坏的复制和粘贴 – 2010-11-09 11:48:26

+1

如果你#include ',你应该使用'std :: printf'。如果你想在不使用std ::的情况下使用printf,请使用'#include '。 – Sjoerd 2010-11-09 12:32:30

6

你忘了拷贝构造函数:

#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)); 
} 

输出:

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 
相关问题