我的代码类似于沿着这些线的东西。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