Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
559 views
in Technique[技术] by (71.8m points)

memory - C++ destructor issue with std::vector of class objects

I am confused about how to use destructors when I have a std::vector of my class.

So if I create a simple class as follows:

class Test
{
private:
 int *big;

public:
 Test ()
 {
  big = new int[10000];
 }

    ~Test ()
 {
  delete [] big;
 }
};

Then in my main function I do the following:

Test tObj = Test();
vector<Test> tVec;
tVec.push_back(tObj);

I get a runtime crash in the destructor of Test when I go out of scope. Why is this and how can I safely free my memory?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem is you don't define a copy constructor for Test. So the compiler generates a default copy constructor for you, which just copies the content of the object - in this case the int pointer.

Now, when you push back your object into the vector, it is implicitly copied with the copy constructor. Which results in two objects pointing to the same array of ints! So in the end, two destructors try to delete the same array - BANG.

Whenever you define a class which owns members via pointers*, apart from the destructor you must also define a copy constructor for it. Update: and an assignment operator, for the same reason (thanks @James :-)

Update2: A trivial way to get around all these restrictions is to define a static array instead of the dynamically allocated one:

class Test
{
private:
  int big[10000];
  // no need for constructors, destructor or assignment operator
};

However, the best practice is to use std::vector<int> instead of an array.

* that is, contains pointers to members with ownership semantics (thanks to @Steve Jessop for clarification)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...