Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my class's destructor get called when I add instances to a vector?

Tags:

c++

stl

vector

It seems that every time I add an object to the vector m_test, the destructor method is called. Am I missing something? How can I prevent this from happening?

class TEST
{
public:
    TEST();
    ~TEST();
    int * x;
};

TEST::TEST()
{
}

TEST::~TEST()
{
... it is called every time I push_back something to the vector ...
    delete x;
}

    vector<TEST> m_test;
    for (unsigned int i=0; i<5; i++)
    {
        m_test.push_back(TEST());
    }
like image 374
2607 Avatar asked Feb 17 '12 16:02

2607


1 Answers

The problem here is that you're violating the Rule of Three. Your class has a destructor so you need a copy-constructor and an assignment operator, too. Alternatively, you could not allow your class to be copied (for example by making T(T const&) and T& operator=(T const&) private, or by deriving from boost::noncopyable), and then resize the vector instead of using push_back.

In the first case, you can just push_back your class as you usually would. In the second, the syntax would be something like

std::vector<TEST> vec(5);
// vec now has five default-constructed elements of type TEST.

Not doing either of these things is a bad idea, as you are very likely to run into double deletion issues at some point -- even if you think you'll never copy or assign a TEST where x != nullptr, it's much safer to explicitly forbid it.

By the way, if you have member pointers that should be deleted when an object goes out of scope, consider using smart pointers like scoped_ptr, unique_ptr and shared_ptr (and maybe auto_ptr if you're unable to use Boost or C++11).

like image 199
Anton Golov Avatar answered Oct 15 '22 06:10

Anton Golov