类对象的std :: vector的C ++析构问题 [英] C++ destructor issue with std::vector of class objects

查看:545
本文介绍了类对象的std :: vector的C ++析构问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我有一个我的类的std :: vector时,我很困惑如何使用析构函数。

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);



当我超出范围时,我在Test的析构函数中遇到运行时崩溃。为什么这样,我如何安全地释放我的记忆?

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?

推荐答案

您的问题在这里:

Test tObj = Test();

Test() code> Test 对象,然后将其复制到 tObj 。此时, tObj 和临时对象都将 big 设置为指向数组。然后临时对象被销毁,调用析构函数并销毁数组。因此,当 tObj 被销毁时,它试图再次销毁已经销毁的数组。

The Test() creates a temporary Test object, which then gets copied to tObj. At this point, both tObj and the temporary object have big set to point to the array. Then the temporary object gets destroyed, which calls the destructor and destroys the array. So when tObj gets destroyed, it tries to destroy the already-destroyed array again.

c $ c> tVec 被销毁,它会销毁它的元素,所以已经销毁的数组将被再次销毁。

Further, when tVec is destroyed, it will destroy its elements, so the already-destroyed array will be destroyed yet again.

定义一个复制构造函数和赋值运算符,以便当复制 Test 对象时,复制 big 数组,

You should define a copy constructor and an assignment operator so that when a Test object gets copied, the big array gets copied, or has some sort of reference count so that it doesn't get destroyed until all owners are destroyed.

一个简单的修复方法是按如下方式定义你的类:

An easy fix is to define your class like this:

class Test
{
private:
 std::vector<int> big;

public:
 Test (): big(10000) {}
};

在这种情况下,您不需要定义任何析构函数,复制构造函数或赋值运算符,因为 std :: vector<> 成员会处理一切。 (但是请注意,这意味着每当复制 Test 的实例时,就会分配和复制10,000个字节。)

In this case, you wouldn't need to define any destructor, copy constructor, or assignment operator, because the std::vector<> member will take care of everything. (But note that this means 10,000 bytes get allocated and copied whenever you copy an instance of Test.)

这篇关于类对象的std :: vector的C ++析构问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆