简体   繁体   English

存储基类指针的C ++向量

[英]C++ vector storing base class pointers

Ok, situation: I am using a library that I have no control over, which has a method createSomeObject(). 好的,情况:我使用的是一个我无法控制的库,它有一个方法createSomeObject()。 This method returns a pointer to an abstract base class with pure virtual functions, and it has no copy constructor so I can't instantiate it myself nor copy it (obviously). 这个方法返回一个指向具有纯虚函数的抽象基类的指针,它没有复制构造函数,所以我不能自己实例化它,也不能复制它(显然)。

I need to store some number (let's say 10) of these in a vector, so I tried to do the following: 我需要在向量中存储一些数字(比如说10个),所以我尝试执行以下操作:

vector<AbstractBaseClass*> v(10);

for(int i = 0; i < 10; i++)
{
    v.push_back(library->createSomeObject());
}

As soon as this loop is over, the vector is filled with broken pointers. 一旦这个循环结束,向量就会被破碎的指针填充。

I have tried the following: 我尝试过以下方法:

vector<AbstractBaseClass*> v(10);

for(int i = 0; i < 10; i++)
{
    AbstractBaseClass* abc = library->createSomeObject();
    v.push_back(abc);
}

To no avail. 无济于事。 I must be going crazy or doing something seriously wrong here. 我必须疯狂或在这里做一些严重的错误。 I've looked around but the answer is always use boost::shared_ptr. 我环顾四周,但答案总是使用boost :: shared_ptr。 A great solution possibly, but I can't guarantee that it'll be on the machines that this will be built on, so I'd like to avoid packaging Boost with the code. 可能是一个很好的解决方案,但是我不能保证它将会在这些将被构建的机器上,所以我想避免使用代码包装Boost。

Is there something I'm missing? 有什么我想念的吗? I feel as though I'm just forgetting some simple thing, as I can't think of a reason one of these wouldn't work. 我觉得好像忘记一些简单的事情,因为我无法想到其中一个不起作用的原因。

When you do this: 当你这样做:

vector<AbstractBaseClass*> v(10);

you're already creating a vector which contains 10 (NULL) pointers. 你已经在创建一个包含10个(NULL)指针的向量。 So after you've called push_back , you'll have a vector with 20 pointers, out of which the first 10 are invalid. 因此,在你调用push_back ,你将拥有一个包含20个指针的向量,其中前10个指针无效。

If you know the size beforehand: 如果您事先知道尺寸:

vector<AbstractBaseClass*> v(10);
for(int i = 0; i < 10; i++)
{
    v[i] = library->createSomeObject();
}

or, alternitively, call reserve after creating an empty vector. 或者,可选地,在创建空向量之后调用reserve

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

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