如何延迟shared_ptr的删除操作

how to defer delete operation of shared_ptr?

本文关键字:ptr 删除 操作 shared 何延迟 延迟      更新时间:2023-10-16

我在main中创建了一个sample类的指针。我把这个指针传递给一个函数function1()。该函数必须使用指针作为共享指针,并使用该指针进行一些操作。在function1()退出时,由于shared_ptr的原因,sample的析构函数被调用。当我将同一个指针传递给不同的函数时,这个指针不再有效,程序崩溃。

1。如何在function1()中延迟删除操作(销毁调用)?

2。什么是替代的方式,这样我就可以传递指针给不同的函数,并安全地使用它,虽然一些函数使用指针作为shared_ptr?

下面是示例代码和输出。

#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] = '';
    sample * s = new sample( data );
    function1( s );
    function2( s );
    return 0;
}
输出:

sample
print_data
data = 123456789
~sample
print_data
data = 

变化

sample * s = new sample( data );

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

并将共享指针传递给所有函数。当该变量超出作用域时,它将被删除,对于您的目的来说已经足够晚了

不应该这样做。如果你想共享一个指针的所有权,那么它应该创建作为shared_ptr,并作为shared_ptr传递给同样想共享所有权的函数。

也就是说,万一你真的知道你在做什么,而且你要修改的东西来完成这个工作,你可以使用一个什么都不做的自定义删除器:

struct null_deleter {
    // Generic so it will work with any type!
    template< typename T >
    void operator()(T *p) const {}
};
void function1( sample * ptr )
{
    shared_ptr<sample> samp( ptr, null_deleter() );
    // I really hope this function isn't expecting
    // me to actually share ownership with it....
    something(samp); 
    ptr->print_data();
}