Vector push_back calls object destructor

Refresh

April 2019

Views

61 time

1

Similar questions have been asked here many times, following the answers didn't solve my problem though.

Let's say I have:

1)Two classes (ACLass and BClass)

2)AClass has a contructor and a destructor

3)BClass has a std::vector member that stores objects of AClass

4)Number of elements in that vector are UNKNOWN beforehand

5)Whenever a BClass method generateObject() is called, the vector expands as a new AClass object is created. This is done by calling std::vector.push_back().

class AClass {
    AClass()  { //Constructor }
    ~AClass() { //Destructor }
};

Class BClass {
    std::vector<AClass> object;

    void generateObject() {
        object.push_back(AClass());
    }
};

Now, in the example above, generateObject() will work only a couple of times. As soon as the vector becomes too small to hold all the objects, it performs various internal operations in order to reserve more memory to be able to expand. The problem is that some of (if not all) the AClass destructors are called during the process.

Since the number of elements is unknown, reserving more space for the vector by using reserve() is not an option. Using emplace_back() did not solve my problem as well.

So how do I go about this? Is there a way to prevent the destructors to be called? Is using std::vector in this case a good idea at all?

1 answers

4

When std::vector expands its storage it copies or moves the current objects into the new storage space. The old objects are thrown away, and that inherently involves calling destructors on the old objects.

If destroying old objects isn't desirable, std::deque has more or less the same operations as std::vector, with somewhat more overhead, but without having to reallocate storage.

If memory usage is not an issue, std::list never moves its stored objects, but each element in the list also has a pair of pointers, one pointing to the previous element in the list, and one pointing to the next element.