2010-11-09 67 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 
相關問題