我的代碼類似於沿着這些線的東西。std :: vector構造函數是否不爲每個元素調用對象構造函數?
class A
{
public:
A(int i) { printf("hello %d\n", i); }
~A() { printf("Goodbye\n"); }
}
std::vector(10, A(10));
我注意到hello打印出來一次。 它似乎暗示該向量僅爲元素 分配空間,但不構成它。我如何使它構建10個對象?
我的代碼類似於沿着這些線的東西。std :: vector構造函數是否不爲每個元素調用對象構造函數?
class A
{
public:
A(int i) { printf("hello %d\n", i); }
~A() { printf("Goodbye\n"); }
}
std::vector(10, A(10));
我注意到hello打印出來一次。 它似乎暗示該向量僅爲元素 分配空間,但不構成它。我如何使它構建10個對象?
當您將它傳遞給std :: vector時,該對象只構造一次。然後這個對象被複制10次。您必須在複製構造函數中執行printf才能看到它。
謝謝你解釋它。 – Matt 2010-11-09 11:43:09
A(10)
構造一個臨時對象。只有一次。您的載體的10個元素通過複製構造函數構建。所以,如果你定義一個拷貝構造函數來打印B,你將得到10個B。
定義拷貝構造函數,你將被罰款:
#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));
}
你忘了拷貝構造函數:
#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
不少人看不慣用C風格IO中的C代碼(http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.1) – Flexo 2010-11-09 11:23:52
它只是一個前足夠好嗎? – Matt 2010-11-09 11:35:57