<p>When returning objects from a class, when is the right time to release the memory?</p>

<p>Example,</p>

<pre><code>class AnimalLister 
{
  public:
  Animal* getNewAnimal() 
  {
    Animal* animal1 = new Animal();
    return animal1;
  }
}
</code></pre>

<p>If i create an instance of Animal Lister and get Animal reference from it, then where am i supposed to delete it?</p>

<pre><code>int main() {
  AnimalLister al;
  Animal *a1, *a2;
  a1 = al.getNewAnimal();
  a2 = al.getNewAnimal();
}
</code></pre>

<p>The problem here is AnimalLister doesnot have a way to track the list of Animals Created, so how do i change the logic of such code to have a way to delete the objects created.</p>

I advise returning a
```
std::tr1::shared_ptr
```
(or
```
boost::shared_ptr
```
, if your C++ implementation does not have TR1) instead of a raw pointer. So, instead of using
```
Animal*
```
, use
```
std::tr1::shared_ptr<Animal>
```
instead.
Shared pointers handle reference tracking for you, and delete the object automatically if there are no references left to it.