Object deletion from heap space - c++

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.

Related

Will this completely clean up the result of dynamic allocation of a class object?

So I dynamically allocated a class object with this code:
void Inventory::createNewInventoryItem(std::string itemName, unsigned int maxQuantity, unsigned int orderThreshold, double price)
{
InventoryItems* newItem = new InventoryItems;
newItem->createInventoryItem(itemName, maxQuantity, orderThreshold, price);
m_inventory.push_back(newItem);
}
Which is stored in this vector: std::vector<InventoryItems*> m_inventory;
Then once the object is done being used deleteInventoryItem is called, which is defined as:
void Inventory::deleteInventoryItem(int posInVector)
{
m_inventory.at(posInVector)->~InventoryItems();
m_inventory.erase(m_inventory.begin() + posInVector);
}
My question is: Will this deleteInventoryItem function successfully free up the memory used by the dynamic allocation in createNewInventoryItem? (This ties into my confusion around if delete[] is needed when a class deconstructor is called)
Sorry for the not "Mission critical" question, just trying to make sure I'm not continuing bad practices as I'm really trying to program as perfectly as I could...
Will this deleteInventoryItem function successfully free up the memory used by the dynamic allocation in createNewInventoryItem?
No, your code does leak memory. What you do here,
m_inventory.at(posInVector)->~InventoryItems();
is explicitly calling the destructor of the container element. This does clean up any resources held by the specific object, but not the memory resource that hosts the object itself. It is very, very rare that you have to manually call the destructor of an object (the only situation I can think of is using placement new, and you very rarely need that).
What you could have done is using delete to both clean up the memory and invoke the destructor of the element being erased. But as a much safer alternative for this manual memory management, I would advise you to choose one the following two options
If the object that is supposed to be stored in the container fine with being copied by value (i.e. not a polymorphic type and you want to store base class references), just store it by value:
std::vector<InventoryItems> myData;
Otherwise, store a std::unique_ptr which takes care of all the memory managent for you:
std::vector<std::unique_ptr<InventoryItems>> myData;
No it will memory-leak. You are obviously calling the destructor but do not call delete which is the counterpart of new. The new followed by a type allocates memory first then calls implicitly the destructor. The delete operator also does two things, first calling the destructor, then deallocate the memory.
There is rarely a need for explicitly calling the destructor, specifically for cleaning up instances created through the new placement syntax., and not calling ~ it in this case will lead to leaks if the instance contains hold dynamically bound resources via members or base class(es).
As a rule of thumb, keep these pairs in mind:
obj = new Class; needs delete obj;
obj = new (buffer) Class needs obj->~Class();
array = new Class[count]; needs delete [] array;
... and, as the most important in the collection, automatic objects:
Class obj; needs (nothing) but the end of the enclosing scope
The last "pair" shows an implicit call to (default) constructor (it could be any other constructor provided by the Class definition) and ends (at the closing brace) with an implicit call of the destructor, which, by the way, the reason for the C++ language to limit the destructors of a class to at maximum one: The compiler depends on this uniqueness to be able to automatically close scopes. This very automatism also forms the basis for std::unique_ptr and std::shared_ptr.

When should I provide a destructor for my class?

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

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!

Do Default Destructors Do Anything?

I was wondering if default class destructors actually do anything when they're called.
I have been researching it and I've found that if I create a class with a function that calls its own destructor it doesn't do anything at all (i.e. all variables remain untouched and the instance still exists and is usable).
Does this mean that a class destructor can be thought of as an inherited virtual function that all classes have and a redefinition of it is possible (to delete pointers etc. and to clear member variables) but that if it's not redefined that it'll do nothing at all?
If so, couldn't a destructor essentially be used as a "clear all data" kind of function and make some parts of code more efficient by clearing a dynamically memory allocated variable and re-using it rather than getting the computer to find a new block of memory on the heap?
Thanks.
Default constructor calls the default constructor of all member variables, not including primitive types (char, int, pointers).
Destructor can be called explicitly, but it does not mean the dellocation of the object. If the object is on the stack, then it can not possibly do anything with it.
Destructors are not virtual by default, but they really should be if you plan to inherit from the class.
If the object is deallocated (goes out of scope, deleted from heap, or enclosing object is desctucted by any means) the desctuctor will be called.
I have been researching it and I've found that if I create a class with a function that calls its own destructor it doesn't do anything at all (i.e. all variables remain untouched and the instance still exists and is usable).
Consider this code:
#include <iostream>
struct A
{
~A()
{
std::cout << "A::~A" << std::endl;
}
};
struct B
{
A a;
};
int main()
{
B b;
std::cout << "Calling b.~B()" << std::endl;
b.~B();
std::cout << "Done" << std::endl;
}
You'll see that calling B's default destructor calls A's destructor, because B contains an A:
Calling b.~B()
A::~A
Done
A::~A
Only when b goes out of scope is the stack unwound and the synthesised B::~B() called and, in turn, A::~A() before their memory is free'd.
In addition to Notinlist's answer:
Default constructors call your base classes' constructors.
If so, couldn't a destructor essentially be used as a "clear all data"
kind of function and make some parts of code more efficient by
clearing a dynamically memory allocated variable and re-using it
rather than getting the computer to find a new block of memory on the
heap?
You're sort of describing a memory pool. If you want, your objects may acquire and return memory buffers to/from some pool system you invent. But for the most part allocations are fast enough and infrequent enough that it's not common (anymore) for people to do this. Not to say they are infrequent, but they need to be happening a lot to take notice of that performance hit.
Calling a destructor manually is generally a bad idea. The C++ FAQ section about destructors has plenty of good information about this.
If you do want to destroy an object explicitly you can use additional scopes to cause the destructor to be safely called (see this FAQ entry). This method also prevents you from using the object instance which has been destroyed. Although the instance may seem to be usable, it really is not.
If your intention is to free some, but not all, of the resources owned by an instance of a class you could try two things:
Define a clear() (or similar) method on the class.
Ensure that the invariant of the class is maintained after clear() is called.
Suppose that your initial approach to manually calling a destructor worked, or you chose to do something that like the clear() method above, in both cases you may run into problems later.
A well understood and often practiced method of resource management in C++ is Resource Acquisition Is Initialization (often abbreviated RAII, but ignore the name if it is confusing, the concept is understandable). See this Wikipedia article or this answer for useful information.
Here is the tl;dr though:
The lifetime of a resource should always be tied to the lifetime of
an object.
The lifetime of an object begins when the constructor completes
The lifetime of an object ends when the destructor completes.
Following this idiom will usually prevent C++ resource management problems before they occur.

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