简体   繁体   中英

Vector push_back calls object destructor

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?

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.

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