销毁vc中的对象 [英] destroy Objects in vc

查看:91
本文介绍了销毁vc中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好

我想知道如何销毁VC ++中的对象
我创建一个函数


//test.h

test
{
 public :
    void add(-------)
}


// Another file using test.h

#include "classtest.h"
#include "test.h"

void classtest::testObjects(-------) 
{

  test testObj1;
    testObj1.add(------)


// now here i want to destroy the object testObj1 how to destroy it.

}



在上面的示例中,由于类实例是在堆栈上创建的,因此在函数结束时会自动将其删除,因为它超出了范围.
即-函数的右大括号}之后,您的对象不再占用内存.

至于创建和删除对象,您可以这样:

测试* testObj;
testObj =新测试;
..
使用testObj的一些操作
..
删除testObj;

请注意,当您创建这样的对象时,它们超出范围将不会被自动删除. (用于指向该对象的4bytes(在32bit sys上)将返回到堆栈,但不会是class对象本身消耗的内存)

如果要将上面的代码更改为:

  void  classtest :: testObjects(-------)
{
 
  测试* testObj1 = 测试;
  testObj1-> add(------)
//  testObj1未删除,这将导致内存泄漏!
} 


Hi All

I want to know how to destroy objects in VC++
AS i create a function


//test.h

test
{
 public :
    void add(-------)
}


// Another file using test.h

#include "classtest.h"
#include "test.h"

void classtest::testObjects(-------) 
{

  test testObj1;
    testObj1.add(------)


// now here i want to destroy the object testObj1 how to destroy it.

}



plz Help

解决方案

In your example above, since the class instance is created on the stack, it is automatically deleted when the function ends, since it goes out of scope.
I.e - your object no longer consumes memory after the closing brace } of the function.

As for creating and deleting objects, you could do so like this:

test *testObj;
testObj = new test;
..
some operations using testObj
..
delete testObj;

Note, that when you create objects like this they will NOT be automatically deleted when they go out of scope. (The 4bytes(on a 32bit sys) used to point to the object will be returned to the stack, but the memory consumed by the class object itself, won''t be)

If you were to change your code above to:

void classtest::testObjects(-------) 
{
 
  test *testObj1 = new test;
  testObj1->add(------)
// testObj1 not deleted, this will cause a memory leak!
}


这篇关于销毁vc中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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