When should I provide a destructor for my class? - c++

This seems like a rather trivial or at least common question, but I couldn't find a satisfying answer on google or on SO.
I'm not sure when I should implement a destructor for my class.
An obvious case is when the class wraps a connection to a file, and I want to make sure the connection is closed so I close it in the destructor.
But I want to know in general, how can I know if I should define a destructor. What guidelines are there that I can check to see if I should have a destructor in this class?
One such guideline I can think of, is if the class contains any member pointers. The default destructor would destory the pointers on deletion, but not the objects they're pointing at. So that should be the work of a user-defined destructor. E.g: (I'm a C++ newbie, so this code might not compile).
class MyContainer {
public:
MyContainer(int size) : data(new int[size]) { }
~MyContainer(){
delete [] data;
}
// .. stuff omitted
private:
int* data;
}
If I hadn't supplied that destructor, than destroying a MyContainer object would mean creating a leak, since all the data previously referenced by data wouldn't have been deleted.
But I have two questions:
1- Is this the only 'guideline'? I.e. define a destructor if the class has member pointers or if it's managing a resource? Or is there anything else?
2- Are there cases when I should not delete member pointers? What about references?

You need to define a destructor if the default destruction does not suffice. Of course, this just punts the question: what does the default destructor do? Well, it calls the destructors of each of the member variables, and that's it. If this is enough for you, you're good to go. If it's not, then you need to write a destructor.
The most common example is the case of allocating a pointer with new. A pointer (to any type) is a primitive, and the destructor just makes the pointer itself go away, without touching the pointed to memory. So the default destructor of a pointer does not have the right behavior for us (it will leak memory), hence we need a delete call in the destructor. Imagine now we change the raw pointer to a smart pointer. When the smart pointer is destroyed, it also calls the destructor of whatever its pointing to, and then frees the memory. So a smart pointer's destructor is sufficient.
By understanding the underlying reason behind the most common case, you can reason about less common cases. It's true that very often, if you're using smart pointers and std library containers, their destructors do the right thing and you don't need to write a destructor at all. But there are still exceptions.
Suppose you have a Logger class. This logger class is smart though, it buffers up a bunch of messages to Log, and then writes them out to a file only when the buffer reaches a certain size (it "flushes" the buffer). This can be more performant than just dumping everything to a file immediately. When the Logger is destroyed, you need to flush everything from the buffer regardless of whether it's full, so you'll probably want to write a destructor for it, even though its easy enough to implement Logger in terms of std::vector and std::string so that nothing leaks when its destroyed.
Edit: I didn't see question 2. The answer to question 2 is that you should not call delete if it is a non-owning pointer. In other words, if some other class or scope is solely responsible for cleaning up after this object, and you have the pointer "just to look", then do not call delete. The reason why is if you call delete and somebody else owns it, the pointer gets delete called on it twice:
struct A {
A(SomeObj * obj) : m_obj(obj){};
SomeObj * m_obj;
~A(){delete m_obj;};
}
SomeObj * obj = new SomeObj();
A a(obj);
delete obj; // bad!
In fact, arguably the guideline in c++11 is to NEVER call delete on a pointer. Why? Well, if you call delete on a pointer, it means you own it. And if you own it, there's no reason not to use a smart pointer, in particular unique_ptr is virtually the same speed and does this automatically, and is far more likely to be thread safe.
Further, furthermore (forgive me I'm getting really into this now), it's generally a bad idea to make non-owning views of objects (raw pointers or references) members of other objects. Why? Because, the object with the raw pointer may not have to worry about destroying the other object since it doesn't own it, but it has no way of knowing when it will be destroyed. The pointed to object could be destroyed while the object with the pointer is still alive:
struct A {
SomeObj * m_obj;
void func(){m_obj->doStuff();};
}
A a;
if(blah) {
SomeObj b;
a.m_obj = &b;
}
a.func() // bad!
Note that this only applies to member fields of objects. Passing a view of an object into a function (member or not) is safe, because the function is called in the enclosing scope of the object itself, so this is not an issue.
The harsh conclusion of all this is that unless you know what you're doing, you just shouldn't ever have raw pointers or references as member fields of objects.
Edit 2: I guess the overall conclusion (which is really nice!) is that in general, your classes should be written in such a way that they don't need destructors unless the destructors do something semantically meaningful. In my Logger example, the Logger has to be flushed, something important has to happen before destruction. You should not write (generally) classes that need to do trivial clean-up after their members, member variables should clean up after themselves.

A class needs a destructor when it "owns" a resource and is responsible for cleaning it up. The purpose of the destructor is not simply to make the class itself work properly, but to make the program as a whole work properly: If a resource needs to be cleaned up, something needs to do it, and so some object should take responsibility for the cleanup.
For instance, memory might need to be freed. A file handle might need to be closed. A network socket might need to be shut down. A graphics device might need to be released. These things will stay around if not explicitly destroyed, and so something needs to destroy them.
The purpose of a destructor is to tie a resource's lifetime to an object's, so that the resource goes away when the object goes away.

A Destructor is useful for when your classes contain Dynamically Allocated Memory. If your classes are simple and don't have 'DAM', then it's safe to not use a Destructor. In addition, read about the Rule Of Three. You should also add a copy constructor and an overloaded = operator if your class is going to have 'DAM'.
2) Do not worry about References. They work in a different way such as that it "Refers" to another variable (Which means they don't point to the memory).

Related

Do you call delete in destructor in C++?

Let say you have a class like this
class Level
{
public:
Level(std::string);
~Level();
private:
Bitmap* map;
}
and in the class you had this
Level::Level(std::string)
{
map = new Bitmap(path);
}
Was wondering do can you call
Level::~Level()
{
delete map;
}
As I was worried about if the class goes out of scope and I haven't deleted map. Then, wouldn't that cause a memory leak. Do I have to manually call to delete map. As I get crash if I call delete in the constructor in my program.
Like I could add a method to Level called say destroy map where I delete map. But, was wondering why I can't add delete into the destructor.
When the Level object goes out of scope, its destructor will be called, so deallocation of memory is useful because that memory is no longer needed. You can also use a unique_ptr, whereby memory-deallocation performed automatically.
This is why destructors stand for. Destructor is explicitly called when your object goes out of scope (memory residing on the stack objects) or when delete is called ( for dynamically allocated objects), so that the memory the object kept would be released. If you want to release member objects memory when destroyed, you can call the destructors of each object using delete (or delete[] for arrays). It is better that you use smart pointers, to avoid unintentional memory leaks and to ensure the memory is freed correctly in all cases, as they use RAII concept (RAII and smart pointers in C++).
Answers already have pointed out that you can trust your destructor to be called when your object goes out of scope. I won't reiterate that. I just wanted to point out that there is no need to allocate your Bitmap with new (unless you were using custom memory allocators, which is not the case here). You can construct it with an initialiser list:
class Level
{
public:
Level(std::string);
private:
Bitmap map;
};
Level::Level(std::string)
: map(path)
{
}
Now it has automatic scope and you don't have to worry about your destructor.
That's basically right.
However:
You need to make sure you create a copy constructor and assignment operator too, if you are managing memory this way. (That's where your crash comes from.)
An alternative, the best way, is to use RAII and store not a raw pointer but a scoped or automatic pointer. Or even just a directly encapsulated object! Then you don't need the delete at all.
As I was worried about if the class goes out of scope and I haven't deleted map. Then, wouldn't that cause a memory leak.
You're right - you should delete map exactly as your code does. But, you should also make your object non-copyable (derive from boost or C++11 noncopyable base classes, or add a private declaration (with no definition/implementation) of the operator= copy assignment and copy constructor. Otherwise, if you (deliberately or accidentally or incidentally - e.g. when storing your object in a container that sometimes copies it around, such as a std::vector) copy your object, then the first copy destructored will delete the map, any other copy that tries to use it will likely crash, and any other copy's destructor that also tries to delete it will also have undefined behaviour.
Do I have to manually call to delete map.
Yes, in your code you do.
A better alternative is to use a smart pointer whose own destructor will delete the pointed-to object.
As I get crash if I call delete in the constructor in my program.
Well, if you call delete after the new, then the constructor won't crash, but you wouldn't have a map object to use after the constructor returns, and if you then try to delete it again in the destructor the you get undefined behaviour which may well manifest as a crash.
If you want to delete the map earlier than the destructor sometimes, you can set the pointer to NULL so that a future delete will do nothing safely. You should then check for NULL before trying to use the map.
Like I could add a method to Level called say destroy map where I delete map. But, was wondering why I can't add delete into the destructor.
As above, you can have destroy_map, but it must coordinate with the destructor.
When there's no compelling reason to do otherwise, it's better to make the map member data, not storing it by reference. When a pointer is useful, use a smart pointer if at all possible. If you want to implement explicit manual memory management, be wary of the issues above.
This is an unusual way to do it. Normally, an object's lifetime is determined by factors outside of the object.
But in fact MFC used to (still does?) do exactly this when a Window is being destroyed. (In response to WM_NCDESTROY, I believe.) This ensures you don't have the Window instances leaking memory after the window is gone.
So I would say it is valid in some cases. You might call it class suicide!

Why use smartpointers?

When in particular are smart pointers good to use, and why use a smart pointer anyway if pointers in C++ are discouraged to use? As an example:
class Object { }
smart_pointer < Object > pInstance;
//wherein I can use the very simple way
Object instance;
Smart pointers are good when you need to maintain ownership of an object. Using them will ensure proper destruction. When pointer is treated as a reference, using smart pointer can sometimes be worse (for example, in terms of performance).
Pointers are an essential part of C++, but using them got much easier as smart ones in C++11 with move semantics introduced (which essentially made unique_ptr possible). That's why in modern code you should always use std::unique_ptr or std::shared_ptr if available.
Edit: You asked for an example, where a pointer could be beneficial to use. The most common problem that I can think of is an optional component of some system. This component will use a lot of memory, so you don't want to always allocate it, neither you control its allocations (so it can't be in "empty" state itself, i.e. is not nullable). Boost.Optional and C++14-ish std::optional allocate memory of the POD-ish size of T, so they won't do. Using a pointer you can optionally allocate that memory:
class Outer {
std::unique_ptr<BigInner> optionalComponent;
public:
void initializeOptionalComponent() {
optionalComponent = new BigInner();
}
void useOptionalComponent() {
if (!optionalComponent)
// handle the error
// operate
}
};
That will solve the problem, but will introduce the obvious, another problem: optionalComponent can be null, which requires all functions using it to check for valid state at all times. Had it been a plain by-value member, it would (or at least should) be always in valid state. As such, if you don't need a pointer, don't use it at all, use vector<MyClass> and plain members.
Anyway, using smart pointer in this case allows you to keep the Rule of Zero; you don't have to write destructor, copy constructor or assignment operator, and the class will behave safely.
Quick answer : smart pointers are useful for (notably)
Enforcing RAII
Managing pointers ownership
Enforcing RAII
One problem that comes with pointers and cause (in many way, some obvious, some twisted) crashes in your program is that you are responsible for the memory underneath them. That means that when you allocate memory dynamically (through new), you are responsible for this memory, and must not forget to call delete. That means it will happen, and worse, there are case where even if you didn't forget, the delete statement will never be reached.
Consider this code :
void function(){
MyClass* var = new MyClass;
//Do something
delete var;
}
Now, if this function throw an exception before the delete statement is reached, the pointer will not be deleted... Memory leak !
RAII is a way to avoid this :
void function(){
std::shared_ptr<MyClass> var(new MyClass);
//Do something
//No need to delete anything
}
The pointer is held by an object, and deleted in its destructor. The difference with the previous code is that, if the function throw an exception, the destructor of the shared pointer will be called and the pointers will thus be deleted, avoiding a memory leak.
RAII takes advantages of the fact that when a local variable goes out of scope, its dtor is called.
Managing pointers ownership
Note which smart pointer I used in the previous example. The std::shared_ptr is a smart pointer that is useful when you pass pointers around. If many part of your code need a pointer to the same object, it can be tricky to decide where it should be deleted. You might want to delete the pointer somewhere, but what if another part of your code is using it ? It results in an access to a deleted pointer, which is not desirable at all ! std::shared_ptr helps prevent this. When you pass a shared_ptr around, it keeps track of how many part of the code have a reference to it. When there isn't any reference to the pointer anymore, this pointer deletes the memory. In other terms when nobody uses the pointer anymore, it is safely deleted.
There are other kind of smart pointers that address other issue, like std::unique_ptr which provide a pointer that is the only owner of the pointer underneath it.
Note - Small explanation on polymorphism
You need pointers to use polymorphism. If you have an abstract class MyAbstract (that means, it have at least one virtual, say doVirtual()), it cannot be instantiated. The following code :
MyAbstract var;
won't compile, you'll get something along the line of Can't instantiate abstract class from your compiler.
But this is legal (with both ImplA and ImplB inheriting publicly from MyAbstract:
MyAbstract* varA = new ImplA;
MyAbstract* varB = new ImplB;
varA->doVirtual(); //Will call ImplA implementation
varB->doVirtual(); //Will call ImplB implementation
delete varA;
delete varB;

Object deletion from heap space

In main function I create an object using new and don't delete it.I hope the heap space would be cleared once the process exits .The below is a sample code where object of class A is a member variable of class B. Class B also has a multimap as a member variable.
Class A
{
Public:
A(); //have definition in cpp file
~A();//have definition in cpp file
Private:
Int a;
};
Class B{
Private:
Std::multimap<string,string> map_test;
Public:
A a;
B(); //have definition inn cpp file
~B();//does not have any definition in cpp file
};
int main()
{
B *b = new B();
/* code section where it fills some 1000 key value pairs in the multimap
for some purpose */
return 0;
}
My understanding:
Even if i do not delete the object here, it won't create any issue as the heap space would be cleaned once the process exits.As my scope of the programme is limited as above and nobody else is going to reuse this.So is it good or bad not to use delete? What's your suggestion on this?
It should call the object's default destructor which then calls the implicit multimap destructor. So its not needed to explicitly clear the multimap.Please correct me if i am wrong.
In parent class it just declares the destructor and does not have any definition.So will it call implicit destructor or it will ignore calling it?(There is no reason of not defining it, just asking for better understanding. )
If it calls implicit destructor in case of parent class, should it call the child class destructor which is defined here?
As the parent class object is instantiated using new, it would be created in heap.Then where exactly the member variables of this parent object would be stored.For example object "a" is a member variable and by looking into the declaration of this member object, seems like it would be created in stack. I am just confused here how the parent object and its member child object exact memory creation happens. Can you please help me to understand this?
Yes, as long as your object is created in main.
However, if you ever want to alter this and for example create multiple instances of B, or use it inside another class, etc etc etc, that's a different story. Also, memory checking tools like valgrind are going to give you false positives on a new w/o delete which you will be tempted to ignore. But then, you may ignore a true memory leak if it becomes a habit.
Correct, now if it was a map<string, string*> then you would likely need to clean up
It will call default destructor
Yes it will
I guess, you are asking where base class member variables are stored ? They are also stored on the heap. They precede derived class fields in memory.
You have asked many question.
First its best practice to alwsys clear your memory even if the process exits and clears all the memory ( as it does) . Always handle it..its easy to do usining shared_ptr...
Destructors always get called in the right order however you multimap is a dangeorus as you should clear the elements in the multimap as ifyou store pointers it can cause a serious leak
Most OSs will clean up a process's heap space when the process exits. I wouldn't be surprised if there are a bunch of embedded OSs out there where that isn't the case, plus it is still bad practise as you do have a memory leak.
As you're leaking the memory, no destructors will be called. That said, if you're not implementing a destructor and rely on the compiler-generated default destructor, you should not declare it either - in fact I'm surprised that you're not getting a linker error. And yes, the default destructor for the multimap will delete the contents of the multimap as long as you observe the container's requirements for value semantics (ie, no raw pointers).
It is bad practise and as a programmer you should really make sure that you always manage your resources properly. Also, I don't see any reason for heap allocating b, you can just create the object on the stack and you won't have to think about resource management.
If you do declare it you'll have to provide an implementation as the declaration of the destructor will implicitly disable the compiler generated destructor. That's why I said above that I'm surprised you're not getting a link error.
The compiler will take care of the destruction of the base classes by walking the hierarchy and calling the destructors in reverse order of construction.
No, the whole object containing both A and B will be constructed on the heap - that's why you can alias a pointer to B as a pointer to A and interact with the derived class as if it was the base class.
Fact : there's no native (under the table) garbage collection in C++, though there are many things that can enforce some sort of garbage collection.
Thus, in your code, you have a memory leak. At the end of the scope in which you allocate a B, the memory you allocated _is not free'd.
Going through your list of questions :
No, if you don't delete the pointer, the memory won't be free'd. There are a few things that you can do regarding this topic :
Use the RAII idiom (Resource acquisition is initialization), i.e. use objects to manage memory :
Use smart pointers : these constructs enforce RAII (the most common in my opinion being std::shared_ptr and std::unique_ptr) and make sure the memory they are responsible for is correctly free'd.
It depends. If you allocated objects using the new operator, then inserted them in the map, but they aren't referenced anywhere else, then you should delete manually every entry of the map. It doesn't apply in this case because the map types aren't pointers.
The class could even omit a destructor declaration. If they are omitted, destructors (but also copy assignement operator, copy constructor and a default constructor) are generated by the compiler.
Edited: It depends, if you declared the member A a;, you don't have to explicitly delete it, its destructor will be called when the class that declares it as a member has its destructor called. but if it's a pointer that you allocated (e.g. in the constructor), then you have to delete it in the destructor.
Once you use dynamic memory allocation for an object, the whole object is on the heap, no matter how his members are declared.

Is "delete this" a bad idea? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Is it safe to delete this?
I've been doing a little work on a class that's designed to act as a node in a linked list, and I figured I'd give the class its own deletion function as opposed to the managing class doing it. So basically it goes like this:
void Class::Delete() {
//Some cleanup code before deleting the object
delete this;
}
Now I've tested this and it appears to work fine, but I've had a problem in the past where objects have been in the middle of running code, been deleted, then obviously crashed the program by trying to use a no-longer-existing object.
Since "delete this" is right at the end of the function, it obviously exits the function and works fine, but is this sort of practice a bad idea at all? Could this ever blow up in my face if I'm not careful?
The FAQlite answers this quite well:
As long as you're careful, it's OK for
an object to commit suicide (delete
this).
Here's how I define "careful":
You must be absolutely 100% positive sure that this object was
allocated via new (not by new[], nor
by placement new, nor a local object
on the stack, nor a global, nor a
member of another object; but by plain
ordinary new).
You must be absolutely 100% positive sure that your member
function will be the last member
function invoked on this object.
You must be absolutely 100% positive sure that the rest of your
member function (after the delete this
line) doesn't touch any piece of this
object (including calling any other
member functions or touching any data
members).
You must be absolutely 100% positive sure that no one even touches
the this pointer itself after the
delete this line. In other words, you
must not examine it, compare it with
another pointer, compare it with NULL,
print it, cast it, do anything with
it.
Naturally the usual caveats apply in
cases where your this pointer is a
pointer to a base class when you don't
have a virtual destructor.
Basically, you need to take the same care as you do with deleteing any other pointer. However, there are more areas where things can go wrong with a member function committing suicide, compared with an explicitly-declared pointer.
Using delete this is a bad idea if one is not sure of the pitfalls & working around them.
Once you call delete this the object's destructor is going to be invoked and the dynamically allocated memory will be freed.
If the object was not allocated using new, it will be a Undefined behaviour.
If any of object's data members or virtual functions are accessed after delete this, the behaviour will be Undefined Behavior again.
Probably, It is best to avoid delete this given the above.
It's actually a frequent idiom, and about as safe as any delete. As
with all deletes, you have to ensure that no further code tries to
access the object, and you have to be sure that the object was
dynamically allocated. Typically, however, the latter is not a
problem, since the idiom is only relevant for objects which have a
lifetime determined by the semantics of the object, and such objects are
always allocated dynamically. Finding all of the pointers too the
object can be an issue (whether delete this is used or not); usually,
some form of the observer pattern will be used to notify all interested
parties that the object will cease to exist.
The idiomatic way of doing that in C++ is by putting the cleanup code in the destructor then let it be called automatically when you delete the object.
Class::~Class() {
do_cleanup();
}
void ManagingClass::deleteNode(Class* instance) {
delete instance; //here the destructor gets called and memory gets freed
}
There's a simple way of doing the same thing that doesn't involve undefined behavior:
void Class::Delete() {
//Some cleanup code before deleting the object
std::auto_ptr delete_me(this);
}

How do I *not* delete a member in a destructor?

I'd like the destructor of my class to delete the entire object except for one of the members, which is deleted elsewhere. First of all, is this totally unreasonable? Assuming it's not, how do I do this? I thought that created an destructor with an empty body would prevent all the members from being deleted (because the destructor wouldn't do anything), but that doesn't seem to be the case.
Short answer: You don't.
Longer answer: If the "member" is actually a pointer to some other allocation, you can arrange to not delete the other allocation.
But usually, if you allocated the other block in the constructor, you want to delete it in the destructor. Anything else will require careful handling of the "ownership" of the block in question. It will be a lot like memory management in plain c. Possible, but fraught with danger.
Good luck.
Depends on what you mean by "deleted". If they aren't in a smart pointer, and aren't explicitly deleted, then they aren't deleted. Members that are just part of the class:
class Bar {
//...
private:
Foo foo;
};
Aren't deleted by the destructor (because they weren't dynamically allocated), they are just destroyed. They "live" inside the class, so once it is destroyed, it's gone.
If you are looking the share "ownership" between two locations, what you want is a dynamically allocated shared_ptr:
#include <memory>
class Bar {
// ...
private:
std::tr1::shared_ptr<Foo> foo;
};
If the member is contained by value (not by pointer or by reference) then you can't prevent it from being deleted and you shouldn't want to.
If you want to delete it elsewhere instead, then make it contained by pointer or by reference.
class House
{
Door door; //contained by value, will be destroyed when the House is
}
class House
{
Door& door; //contained by reference, will not be destroyed when the House is
}
The code in the destructor is only to delete members that are dynamically allocated. The destruction of members is not optional, you can only control the deallocation of what you explicitly allocated before (with operator new).
What you want to do can be obtained using a shared_ptr, in which both your class and the external code share a pointer to the same external object. This way, only when all the pointers to that object go out of scope it will be deleted. But beware not to do circular references, shared_ptr has no "garbage collector" wisdom.
Of course you could use a regular pointer shared by those places, but this is in most cases a bad idea, prone to give you headaches about proper resource deallocation later.
First of all, if the member object is contained by value, it simply goes out of scope when the container object is destroyed, and you cannot prevent it from being deallocated automatically.
If, instead, it is indirectly referenced by your container object (for example with a pointer), you don't have to do anything in particular to not delete it. The destructor doesn't delete anything unless you explicitly write the code to do so.
As for the question whether this is unreasonable, I think it is not, in general, but you have to make clear (usually in the documentation, since C++ has no language support for this concept) what is the object that owns the member in question.
I think that in most cases you're asking for trouble if you don't destruct the entire object in the same action. It sounds like your class should have a clean up method for that member, which is called within the destructor. If for some reason the member has to be destroyed sooner, the method can return early.
First of all, is this totally
unreasonable?
I wouldn't say unreasonable, perhaps questionable.
It's perfectly valid for one class to own and therefore should take care of clean up, while at the same time having a reference or a pointer to that object in another class.
However, it might be questionable if the second class reall should have that pointer or not, I'd prefer to always use a get-method to retrieve that pointer whenever I need it, e.g. by calling a parent class or some resource manager.
If you have dynamically allocated memory for this member it is possible once you have shared the reference to this member before destroying the object and if you ensure the member is not destroyed in the object's destructor. However I think this practice isn't so reasonable.
When you talk about class members being deleted in the destructor, you have to make a distinction between members that are not pointers and those that are. Let's say you have a class like this:
class Foo
{
public:
Foo() {p = new int;}
~Foo(){}
private:
int a;
int *p;
};
This class has 2 data members: an integer a and a pointer to an integer p. When the destructor is called, the object is destroyed, meaning that the destructors for all its members are called. This happens even if the destructor's body is empty. In the case of a primitive type, like an integer, calling its destructor just means that the memory it occupies will be released. However, there is a catch when you destroy a pointer: whatever it points to does not get destroyed by default. For that you have to explicitly call delete.
So in our example, a will be destroyed when the destructor is called, and so will p, but not whatever p points to. If you wish to free the memory to which p points, the destructor for Foo should look like this:
~Foo() {delete p};
So, getting back to your question, all the members of your class which are not pointers will be destroyed no matter what, when the object's destructor is called. On the other hand, if you have members that are pointers, whatever they point to will not be destroyed, unless you specifically call delete for them in the destructor.
How come no one mentioned weak and strong pointers?
A strong pointer is a smart pointer that acts normally.
A weak pointer is a smart pointer that cannot delete itself unless all of the strong pointers are out of scope.
Strong pointer indicates ownership, a weak pointer indicates sharing.
Look at boost.shared_ptr and boost.weak_ptr and Loki's StrongPtr for implementations.
Also take a look at RAII. If you knew RAII you would have known the answer to this question yourself.
It is not unreasonable, but care should be taken to ensure that cleanup of any managed resources is handled implicitly.
(The first managed resource that people generally worry about is memory, but anything that can leak - memory, file handles, IDispatch pointers - should have code which handles the cleanup implicitly).
For managed resources shared by multiple objects (almost certainly the case if "this object" is supposed to have a pointer to something that gets cleaned up by "that object"), you are normally needing either a "reference counted pointer" to manage the object or a "weak pointer", depending on your lifetime requirements.
For managed resources which are not shared (and in particular those that need to be managed properly when exceptions can be thrown), then an auto_ptr or other variant may be more suitable.
The Scott Meyers Effective C++ books were a reasonable starting point for learning about smart pointers, but in practice you should probably just grab a vetted library like Boost and let somebody else worry about getting the obscure corner cases (like what happens if a constructor throws an exception?) right.
This is possible but basically as #dmckee said it is then a ownership issue. If that is the case may be you can go for refcounting. i.e.
class A
{
RefObj* obj;
A()
{
obj = new RefObj;
}
~A()
{
obj->ReleaseRef();
}
}
RefObj
{
int m_iRefCounter;
RefObj()
{
m_iRefCounter = 1;
}
AddRef()
{
m_iRefCounter++;
}
ReleaseRef()
{
m_iRefCounter--
if(m_iRefCounter == 0)
{
delete this;
}
}
}
}