Search code examples
c++pointersshared-ptrsmart-pointers

how to defer delete operation of shared_ptr?


I have created a pointer of sample class in main. I am passing this pointer to a function function1(). This function has to use pointer as shared pointer and do some operations using this pointer. During exit of function1() destructor of sample in invoked due to shared_ptr. When I pass the same pointer to different function, this pointer is no more valid and program crashes.

1.How do I defer delete operation ( destruction invocation) in function1()?

2.What is the alternative way, so that I can pass pointer to different functions and use it safely, though some of the function are using pointer as shared_ptr?

Here I have sample code and output.

#include <memory>
#include <iostream>
#include <string.h>

using namespace std;

class sample
{
    private:
        char * data;

    public:
        sample( char * data )
        { 
            cout << __FUNCTION__ << endl;
            this->data = new char[strlen( data)];
            strcpy( this->data, data ); 

        }
        ~sample()
        {
            cout << __FUNCTION__ << endl; 
            delete this->data; 
        }
        void print_data()
        { 
            cout << __FUNCTION__ << endl;
            cout << "data = " << this->data << endl;
        }
};

void function1( sample * ptr )
{
    shared_ptr<sample> samp( ptr );
    /* do something with samp */
    ptr->print_data();
}

void function2( sample * ptr )
{
    ptr->print_data();
}

int main()
{
    char data[10] = "123456789";
    data[10] = '\0';
    sample * s = new sample( data );

    function1( s );
    function2( s );

    return 0;
}

output:

sample
print_data
data = 123456789
~sample
print_data
data = 

Solution

  • Change

    sample * s = new sample( data );
    

    into

    shared_ptr<sample> s(new sample( data ));
    

    and pass the shared poiter to all functions. It will be deleted when this variable gets out of scope, so late enough for your purposes