简体   繁体   中英

C++ vector storing base class pointers

Ok, situation: I am using a library that I have no control over, which has a method 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:

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. 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.

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. So after you've called push_back , you'll have a vector with 20 pointers, out of which the first 10 are invalid.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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