如何延迟shared_ptr的删除操作
how to defer delete operation of shared_ptr?
我在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();
}
相关文章:
- 将数组的地址分配给变量并删除
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- C/C++编译器通常会删除重复的库吗
- 从链接列表c++中删除一个项目
- C++如何通过用户输入删除列表元素
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 是否需要删除包含对象的"pair"?
- 如何在自删除后将对象设置为nullptr
- 删除[] 的行为 (ptr, 0)
- 唯一/共享 ptr 用于在数组超出范围后自动删除阵列
- 如何从集合中删除共享的 PTR 元素
- C++14 unique_ptr并使用已删除的函数'std::unique-ptr' unique_ptr错误
- 删除PTR C 后会发生什么
- 如何删除带有 int ptr 指向它的数组
- 数据突然从 Boost shared_array/ptr 中删除
- c++中新建和删除ptr包装器类
- 删除ptr时堆损坏
- openv Ptr类.指针对象在调用函数后被删除
- 删除从函数返回的唯一ptr
- 当可以在类对象超出范围之前删除此数据时,类允许访问其数据(通过 ptr/it)是否设计不好