如何推迟shared_ptr的删除操作? [英] how to defer delete operation of shared_ptr?
问题描述
我在main中创建了sample
类的指针.我正在将此指针传递给函数function1()
.该函数必须使用指针作为共享指针,并使用该指针执行一些操作.在function1()
退出期间,由于shared_ptr
而调用了sample
的析构函数.当我将相同的指针传递给不同的函数时,该指针不再有效,并且程序崩溃.
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.如何延迟function1()
中的删除操作(销毁调用)?
1.How do I defer delete operation ( destruction invocation) in function1()
?
2.另一种方法是什么,以便我可以将指针传递给不同的函数并安全地使用它,尽管某些函数将指针用作shared_ptr?
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;
}
输出:
sample
print_data
data = 123456789
~sample
print_data
data =
推荐答案
更改
sample * s = new sample( data );
进入
shared_ptr<sample> s(new sample( data ));
,并将共享的Poiter传递给所有函数.当此变量超出范围时,它将被删除,因此为您的目的已经足够晚了
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
这篇关于如何推迟shared_ptr的删除操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!