Home > Enterprise >  Does creating an object directly in a vector, and then removing it from the vector, calls to a destr
Does creating an object directly in a vector, and then removing it from the vector, calls to a destr

Time:01-02

Say i have a class named test, and a vector

std::vector<test> Tests;

If i execute this code:

Tests.push_back(test());

and then

Tests.pop_back();

What happens to the test object? Is its destructor being called upon?

CodePudding user response:

This example might show a little bit better what happens.

Live demo here : https://onlinegdb.com/c6-N-vyPc


Output will be :

Creating first vector (push_back)
>>>> Test constructor called
>>>> Test move constructor called
<<<< Test destructor called
Destroying first vector
<<<< Test destructor called

Creating second vector (emplace_back)
>>>> Test constructor called
Destroying second vector
<<<< Test destructor called

Example code :

#include <iostream>
#include <vector>

class Test
{
public:
    Test()
    {
        std::cout << ">>>> Test constructor called\n";
    }

    Test(const Test&)
    {
        std::cout << ">>>> Test copy constructor called\n";
    }

    Test(Test&&)
    {
        std::cout << ">>>> Test move constructor called\n";
    }

    ~Test()
    {
        std::cout << "<<<< Test destructor called\n";
    }
};


int main()
{
    // scope to manage life cycle of vec1
    {
        std::cout << "\nCreating first vector (push_back)\n";
        std::vector<Test> vec1;
        vec1.push_back(Test{});
        std::cout << "Destroying first vector\n";
    }

    // scope to manage life cycle of vec2
    {
        std::cout << "\nCreating second vector (emplace_back)\n";
        std::vector<Test> vec2;
        vec2.emplace_back();
        std::cout << "Destroying second vector\n";
    }

    return 0;
}
  •  Tags:  
  • c
  • Related