所以在我的工作中,我无法访问完整的std库,因为......只是因为(公司无意义的原因)。我不能使用unique_ptr但我可以访问shared_ptr而且我正在使用c ++ 11。所以......
我正在使用一个预先存在的(内部)库函数来为我获取数据并通过原始点返回它(比如uint8_t *)。我希望将这些数据作为shared_ptr存储在我的课程中。
根据Will a shared_ptr automatically free up memory?
和http://herbsutter.com/2013/05/29/gotw-89-solution-smart-pointers/
看来如果我在堆上分配内存并将其存储在shared_ptr中,智能指针应该为我释放内存(uint8_t *数据)。这是真的?任何文学链接都会有所帮助。此外,从这些链接看来我似乎不能使用make_shared因为我“从其他地方采用原始指针。”
class myClass
{
public:
shared_ptr<uint8_t> iv_data;
// rest of class
};
data_size = getDataSize(...); // legacy internal function
uint8_t* data = new uint8_t[data_size];
getData(data, data_size); // legacy internal function
myClass object;
object.iv_spd_data = std::shared_ptr<uint8_t>(l_spd_data);
// if scope ends here will I get a memory leak for not freeing data
答案 0 :(得分:0)
我想那行:
object.iv_spd_data = std::shared_ptr<uint8_t>(l_spd_data);
应该:
object.iv_data = std::shared_ptr<uint8_t>(l_spd_data);
?
shared_ptr
可以与其他shared_ptr
个对象共享指针的所有权。当拥有指针的shared_ptr
的最后一个被销毁时,指针所指向的对象将被删除。
使用object.iv_data = std::shared_ptr<uint8_t>(l_spd_data);
创建临时shared_ptr并将其分配给object.iv_data
。实际上,您在l_spd_data
和临时object.iv_data
之间共享shared_ptr
的所有权。由于临时shared_ptr在此语句之后被销毁,因此唯一的所有者现在是object.iv_data
。销毁myClass object
后,iv_data
将被销毁并l_spd_data
被删除。
所以在这种情况下你不会得到内存泄漏。
答案 1 :(得分:0)
以下是将shared_ptr<>
与数组类型和自定义删除器一起使用的示例。我已经添加了一些打印语句来显示程序的流程。请注意,您不需要知道删除时分配的大小,只需要知道类型是数组。不为delete[]
删除已分配的数组是未定义的行为;这就是需要自定义删除器的原因。
#include <iostream>
#include <memory>
#include <cstdint>
using namespace std;
template< typename T >
struct array_deleter
{
void operator ()( T const * p)
{
cout << "using delete[]" << endl;
delete[] p;
}
};
int8_t* allocate_func()
{
cout << "allocating array" << endl;
return new int8_t[10];
}
int main() {
int8_t *ptr = allocate_func();
cout << "creating smart pointer" << endl;
shared_ptr<int8_t> sptr(ptr, array_deleter<int8_t>());
cout << "exiting main" << endl;
return 0;
}