我有一个指针作为成员的结构:
struct MyStruct {
char *ptr;
}
我想在范围内初始化ptr,然后能够在该范围之外使用它:
{ // scope 0
{ //scope 1
{ // scope 2
mystruct.ptr = new char[100];
}
// mystruct.ptr still lives here
}
// i dont need mystruct anymore
delete[] mystruct.ptr;
}
但后来我必须删除它,这很容易出错,我宁愿避免这样做。所以我想用std::shared_ptr
。
{ // scope 0
{ //scope 1
{ // scope 2
auto a = std::make_shared<char>(new char[100]);
mystruct.ptr = a.get(); // ??????? HOW TO ASSIGN
}
// mystruct.ptr still SHOULD live here
}
}
那么,我怎么能这样做?我应该如何将shared_ptr分配给mystruct.ptr以使所有权计数变为2?我看到get()不起作用,因为它只是传递指针而不是给予所有权,因此它被删除。
如你所见,这里的主要动机是延长寿命,所以我对其他做法持开放态度。也许我想在这里使用shared_ptr是错误的?
答案 0 :(得分:3)
除了将std :: shared_ptr的所有权计数器分配给另一个std :: shared_ptr实例之外,没有合法的方法来增加它。无论如何,它无法解决您的问题。在你的情况下,你必须照顾适当的新/ malloc和免费/删除你的已用内存。如果你操纵一个share_ptr,你必须小心你也减少它,否则你的内存泄漏。情况也是如此。