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.
Related
I was experimenting with destructors in C++ with this piece of code:
#include <iostream>
struct temp
{
~temp() { std::cout << "Hello!" << std::endl; }
};
int main()
{
temp t;
t.~temp();
}
I see that "Hello!" is being printed twice. Shouldn't the calling of the destructor free the object and the destructor shouldn't be called again when it goes out of scope? Or is there some other concept?
(I do not intend to do this in practice. I'm just trying to understand what's going on here.)
It happens because you told it to happen. The destructor for an automatic variable is always called when the variable goes out of scope. You also called it. That's two calls total.
Calling an object's destructor does not signal to C++ not to call it again, since in normal execution there is no need to keep track.
The solution is to never manually call your destructor.
Calling the destructor does not free the object.
The destructor is there to clean up the internals of the object and then the object itsself is freed after the destructor finishes.
It's an error to do what you are doing similarly to the way that you can call delete twice on an object but it's an error to do so.
There are only a very few cases where you want to call the destructor manually and this isn't one of them. It's really there for the times you manually construct an object at a memory location using placement new and then need to be able to destruct it without freeing the memory.
I see that "Hello!" is being printed twice. shouldn't the calling of the destructor free the object and the destructor shouldn't be called again when it goes out of scope. Or is there some other concept ?
That's correct.
I must mention that im not intending to do this in practice. Im just trying to understand whats going on here.
You've called the destructor, preparing an object to be destroyed. But this is also done automatically when an object goes out of scope, before it's actually de-allocated.
The thing to understand is this: If you do things that don't make sense, then bad things happen. So don't do things that don't make sense. If you manually call a destructor, the descructor runs. That has no effect on anything else unless the destructor actually does something that has an effect.
You just call the destructor, you don't actually free any memory (it is statically allocated). If you use new and then delete the destructor will only be called once.
Destructor is meant to be called when an object goes out of scope if the object is in the stack as in this case or called when it is explicitly destructed with delete when the object is created on the heap with new operator at the first place.
There is no way for the compiler or the run time system to keep track whether the destructor is called by you manually or not. Also it is a very bad practice to make a call to the destructor.
If you want to do some manual cleaning (other than the object being deleted from memory or getting removed from the stack) before the object getting deleted you may do something like this.
Here you want to allow the client to manually clean things, even before the object gets deleted. But in addition to that, you clean things if client misses to clean it.
class A
{
public:
A() : _closed(false)
{}
~A()
{
close();
}
void close()
{
if (! _closed()) {
// close file handles etc.
}
}
private:
bool _closed
}
The destructor is not the "destroyer" of the object. It's just an ordinary function, but it's called automatically by the language immediately prior to the time of destruction.
It's official name is the destructor, but perhaps it would be more easily understood if we called it the "Before-Destruction" function.
You won't need to call to a destructor, although it is possible to do so. The compiler should implicitly run your destructor for you when an object is no longer used. When objects are created, your constructor is utilized for that object, if it has been declared with specific and initialized values for your class members. When you no longer need your object your destructor will run and delete member variable declarations and their values. This is most useful for languages that don't utilize automatic garbage collection, like C++.
You don't call the destructor explicitly, it is called automatically when the variable goes out of scope (here after the return 0; statement). That's why it is called twice, you call it, and then the system calls it.
If you want to be able to remove an instance of this class yourself, explicitly, you need to dynamically allocate it:
temp *t = new temp;
// do stuff with t...
delete t; // do not forget this, or the constructor is not being called at all
You shouldn't actually call the deconstructor. It is called for you by the runtime support. Hence your calling it once and the runtime support is calling it the second time.
Here is some food for thought on destructors:
http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr380.htm
You can explicitly call deconstructors, however it's not recommended, normally they are implicitly called.
The destructor of a class could be invoked:
Explicitly
When the destructor is explicitly invoked using the object of the class, the same way you invoke another member function of the class.
Implicitly
When the object of the class goes out of scope or an object which is created using the new operator is destroyed using the delete operator.
In your sample program, you do both
int main()
{
temp t;
t.~temp(); //1. Calling destructor explictly using the object `t`
return 0;
} // 2. object `t` goes out of scope. So destructor invoked implictly
and that is the reason why you see the destructor being called twice.
As you have aptly thought, the destructor will destroy the resources which were created by constructor. So the destrutor should not be called explicitly, as it will result in destroying the already destroyed resource and that could be fatal.
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).
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.
What is The Rule of Three? mentions
After executing the body of the destructor and destroying any automatic objects
allocated within the body, a destructor for class X calls the destructors for
X's direct [...] members [n3126.pdf 12.4 ยง6]
Which leaves me wondering, what's the use of a destructor if not to destroy the members? Please provide examples
It is for additional cleanup that the members themselves are not responsible for. Or in the case of resource management to make sure the resources associated with he object are correctly released. Remember not all members have destructors that will be called (pointers don't have destructors). So if you have pointers you need to manually manage them.
Example resource management with pointers.
shared_ptr::~shared_ptr()
{
if (decrementReferenceCountAndCheckForZero())
{
cleanupResources();
}
}
Example. Working with frameworks. None of the members know about the framework but the worker does.
MyWorker::MyWorker()
{
Framwork::Register(this);
}
MyWorker::~MyWorker()
{
Framework::Unrigester(this);
}
Anything associated to the class instance that needs disassociation/release/special handling once the object ceases to exist.
Few examples:
File handles opened, owned and used by the instance and wont be used post object destruction.
Socktes, mutex etc opened and owned by the class instance.
All that statement means is if you have a destructor defined as
Foo::~Foo()
{
Bar b;
b.do_whatever();
}
then the b object's destructor is run before the destructors of any of Foo's members. The body of the destructor is executed, and the automatic object allocated within the body, i.e. b, is destroyed first.
Your class might manage resources that aren't released by calling the destructors of the data members of your object. If so, then the code to release the resource belongs in a destructor that you write.
For example if you allocate objects with new then they must be freed with delete. If you open a file with fopen then it's closed with fclose. If you take a Posix mutex with pthread_mutex_lock then it must be released with pthread_mutex_unlock.
For each kind of resource needs freeing you (or someone else) can write a class that manages and frees that resource, and provides access to its basic operations. Hence the existence of classes like std::unique_ptr, std::shared_ptr, std::lock_guard, std::fstream. Of course, for simplicity you usually want there to be only one class that manages a particular kind of resource. So, since std::lock_guard exists in C++11, the only reason that you'd write your own class to release a mutex would be if you're providing some alternative interface to the standard one. Classes with non-default destructors should ideally be rare in your own code -- often there already exist classes that you can use as data members or automatic variables, and whose destructors do the job.
This might help you
Suppose a class is having array of someClass which is dynamically created . In your constructor suppose you created
someClass * p = new someClass [10] ;
then in destructor you would write
delete []p ;
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;
}
}
}
}