在C++中,是使用一个对象的向量一个好主意?如果没有,这个C++代码有什么问题?C++,对象的向量
#include <vector>
using namespace std;
class A {};
int main() {
vector<A*> v (new A);
return 0;
}
从克++:
13: error: invalid conversion from
A*' to
unsigned int'
在C++中,是使用一个对象的向量一个好主意?如果没有,这个C++代码有什么问题?C++,对象的向量
#include <vector>
using namespace std;
class A {};
int main() {
vector<A*> v (new A);
return 0;
}
从克++:
13: error: invalid conversion from
A*' to
unsigned int'
的constructor for std::vector需要的初始长度,而不是元素。
这意味着你通常会怎么做:
你得到编译器错误你是因为你的系统上,size_type
被定义为unsigned int
。它试图使用该构造函数,但失败,因为您将它传递给了一个指针A.
在使用您不知道的东西之前,您需要阅读documentation。
下面是对std::vector
类的不同的构造函数:
explicit vector (const Allocator& = Allocator());
explicit vector (size_type n, const T& value= T(), const Allocator& = Allocator());
template <class InputIterator>
vector (InputIterator first, InputIterator last, const Allocator& = Allocator());
vector (const vector<T,Allocator>& x);
矢量没有一个构造函数一个项目来存储。
为了一个项目的矢量与给定值:
vector<A*> v (1, new A);
至于是否是有指针动态分配对象的vector是一个好主意 - 没有。您必须手动管理该内存。
按值存储对象或者必须使用智能指针来自动管理内存(例如std :: tr1 :: shared_ptr)会更好。
我会建议不要使用std::vector
像这样:内存管理成为一场噩梦。 (例如,vector<A*> v (10, new A);
有十个指针,但只有一个已分配的对象,并且您必须记住只能释放一次。如果您未取消分配,则您的内存不确定。)
请改为使用Boost Pointer Container library:你可以传入新分配的对象,它会为你处理所有的内存管理。