简体   繁体   English

C ++,对象向量

[英]C++, vector of objects

In c++, is using a vector of objects a good idea? 在c ++中,使用对象向量是个好主意吗? If not, what's wrong with this c++ code? 如果不是,那么此c ++代码有什么问题?

#include <vector>

using namespace std;

class A {};

int main() {

        vector<A*> v ( new A);
        return 0;
}

from g++: 从g ++:

13: error: invalid conversion from A*' to unsigned int' 13:错误:从A*' to unsigned int'的无效转换

The constructor for std::vector takes an initial length, not an element. std :: vector构造函数采用初始长度,而不是元素。

This means you'd normally do: 这意味着您通常会这样做:

vector<A*> v(1); // Initialize to length 1
v.push_back( new A() ); // Add your element...

You're getting the compiler error you are because, on your system, size_type is defined as an unsigned int . 您收到编译器错误是因为在系统上, size_type被定义为unsigned int It's trying to use that constructor, but failing, since you're passing it a pointer to an A. 它正在尝试使用该构造函数,但失败了,因为要向其传递指向A的指针。

You need to read the documentation before using something you don't know. 您需要先阅读文档,然后再使用不了解的内容。

Here are the different constructors for the std::vector class: 以下是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 doesn't have a constructor that takes one item to store. Vector没有需要存储一项的构造函数。

To make a vector of one item with the given value: 制作具有给定值的一项的向量:

vector<A*> v ( 1, new A);

As to whether it is a good idea to have a vector of pointers to dynamically allocated objects - no. 关于是否有一个指向动态分配对象的指针向量是否是一个好主意-不。 You have to manage that memory manually. 您必须手动管理该内存。

It's much better to store objects by value, or if you must - use a smart pointer to automate managing memory (eg std::tr1::shared_ptr). 最好按值存储对象,或者如果必须的话,使用智能指针自动管理内存(例如std :: tr1 :: shared_ptr)。

I would recommend not using std::vector like this: memory management becomes a nightmare. 我建议不要像这样使用std::vector :内存管理成为一场噩梦。 (For example, vector<A*> v ( 10, new A); has ten pointers but only one allocated object, and you have to remember to deallocate only once. If you don't deallocate at all, you have unfreed memory.) (例如, vector<A*> v ( 10, new A);具有十个指针,但只有一个已分配的对象,并且您必须记住仅释放一次。如果根本不释放,则您有未释放的内存。 )

Instead, consider using the Boost Pointer Container library : you can pass in newly allocated objects, and it will handle all of the memory management for you. 相反,可以考虑使用Boost Pointer Container库 :您可以传入新分配的对象,它将为您处理所有内存管理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM