Discussion Locked

C++

0 helpful
9 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

Hi All,

I need help in C++ . I want to delete the object explicitly when i want . i dont want to be dependent on complier or garbage collector . I also dont want to use define the scope of the object using "{" and end scope by "}" .

ex:

class base
{
};

void main()
{
base object ;

// some code here

// i want delete object on this line ?

/// some more code

}

thanks a lot

Gaurav

9 replies

by vickydicky

Hi Gaurav,
This is very nice question.Here ans goes.

There r three types of memory used in C++ language,
1) Static: Which ones allocated it will last till the end of ur programme.
2) Stack: Which is like scratch pad which is allocated and remains it till the end of the scope, where it is allocated, and ur asking about the same to delete whenever u want and u don't want to delete it by going out of scope.
3) Heap: Here a memory is allocated and will remain untill u want. So my suggestion is if u want ur object should free the memory when u want allocate this in Heap and not in stack(which u had done in the given ex.) and then using delete keyword provided by C++ language u can free up the resoruces.

Hope this is the ans. of ur question.I am looking forward to ur comments.

by wayne m.

Use brackets to control the life time of your object, i.e.,

void main()
{
{
base object;
//some code here.
} //object destructor called here

// some more code.
}

I would suggest as a follow on step to break out the inner module as its own subroutine. It looks like it is probably doing some well defined operation and should be a logical break out.

by mtadeu

In such cases you should use dynamicly created objects. To do so, use "memalloc"( if you r using a c compiler ) or the "new operator"( c++ compiler ). Remember to deallocate the object from memory.

class base
{
};

void main()
{
// use une of them
base *aux = malloc( sizeof(base) ); // c compiler
base *aux = new base; // c++ compiler

// some code here

// i want delete object on this line ?
free( (void*)aux ); // c compiler
delete aux; // c++ compiler

// some more code

}

Hole it helps,
Miguel Tadeu

by kmerrillt

Are you using a local variable to the function? Wouldn't this control what you're trying to do?

This discussion is closed to new replies.