goldenmean
goldenmean

Reputation: 18956

Using smart_ptr for user defined class objects

As a C++ neophyte trying to understand smart pointers. I have written below code to check.

It did compile and run but I was expecting the destructor of my class to be invoked and print the cout's from the destructor but it didn't .

Do we need to overload any function in the user defined class so that its destructor is called when the smart_ptr object of that class gets destroyed.

Why is that it did not invoke the object destructor. What is that i am missing?

#include <iostream>
#include <cstdlib>
#include <tr1/memory> 
#include <string>

//using namespace std;

class myclass
{
public:
  myclass();
  myclass(int);
  ~myclass();
private:
  int *ptr;
  std::string *cptr;
};

myclass::myclass()
{
    std::cout << "Inside default constructor\n";
}

myclass::myclass(int a)
{
   std::cout << "Inside user defined constructor\n" ;
   ptr = new int[10];
   cptr = new std::string("AD");
}

myclass::~myclass()
{
    std::cout << "Inside destructor..\n";
    delete [] ptr;
    delete cptr;

    std::cout << "Freed memory..\n";
}

int main()
{


   int i;
   std::cin >> i;       
 std::tr1::shared_ptr<std::string> smartstr(new std::string);
 std::tr1::shared_ptr<myclass> smart_a(new myclass(i));
   if(i == 0)
   {
      std::cout << "Exiting...\n";
      exit(-1);
   }


}

Upvotes: 3

Views: 174

Answers (4)

awesoon
awesoon

Reputation: 33661

And, as additional information to other answers, note from the Standard:

Per §3.6.1/4:

Terminating the program without leaving the current block (e.g., by calling the function std::exit(int) (18.5)) does not destroy any objects with automatic storage duration (12.4).

Upvotes: 4

Deepu
Deepu

Reputation: 7610

In the code below,

if(i == 0)
{
   std::cout << "Exiting...\n";
   exit(-1);
}

You are terminating the program by calling exit(), so the object is never destroyed. So remove the exit(-1); from the code.

Upvotes: 2

Captain Obvlious
Captain Obvlious

Reputation: 20063

The reason the object is never destroyed is because you are exiting the program by calling exit. This causes the program to exit before the smart pointer objects have a chance to go out of scope thus the objects they manage are never destroyed. Since you are in main use a return statement instead of calling exit.

Upvotes: 11

Tyler Jandreau
Tyler Jandreau

Reputation: 4335

One possible solution is ensure that your buffer is flushed in your destructor. Use std::endl; in your destructor. For more information, please look here: Buffer Flushing, Stack Overflow

Upvotes: -1

Related Questions