简体   繁体   中英

create vector of objects on the stack ? (c++)

I am creating a temporary vector of pointers to myObject objects. But I am wondering about what happens to the objects I created...

{
    std::vector<myObject *> myVector;
    myVector.reserve(5);

    for (int i = 0 ; i < 5 ; ++i){
        myVector[i] = new myObject();
    }
}

I assume that at the end of the scope myVector is destroyed and all the pointers with it, but as I created the objects with the keyword new , does it means that those objects still exist somewhere on the heap ? Should I destroy them manually before the end of the scope ?

You should use the following

std::vector<std::unique_ptr<myObject>> myVector(5);
for (auto& obj : myVector)
{
    obj = std::make_unique<myObject>();
}

This will create your vector with size 5 , instead of you having to resize it afterwards. On that note, you would have had to do so with resize instead of reserve .

If your vector is of std::unique_ptr , then you don't have to worry about memory management, the pointers will clean themselves up when the vector falls out of scope.

Yes, those objects still exist and you must delete them.

Alternatively you could use std::vector<std::unique_ptr<myObject>> instead, so that your objects are delete d automatically.

Or you could just not use dynamic allocation as it is more expensive and error-prone.

Also note that you are misusing reserve . You either want to use resize , or reserve paired with push_back .

Remember: You Need to destroy every object you created with new !

This means, your objects are not destroyed, only the pointers. You Need to do something like this:

for (int i = 0 ; i < 5 ; ++i){
    delete myVector[i];
}

remember: each new should be 'paired' with delete .

So yes - those objects remain in the heap - you have a memory leak.

Either create a loop calling delete, or change type of vector to store std::unique_ptr<myObject> - this will delete pointers automatically.

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