[英]How do you cast a vector of smart pointers to a constant vector that hold smart pointers that point to constants?
[英]Do you need to tell Smart Pointers when you are done with them
使用智能指针,是否仍然需要释放/重置它们以确保释放内存? 还是可以让它们超出范围?
类成员智能指针的行为是否有所不同-与释放内存,悬空指针有关? 析构函数应该始终释放这些变量吗?
class Foo
{
public:
Foo()
{
myUPtr = std::unique_ptr<int>(new int);
mySPtr = std::shared_ptr<int>(new int);
}
~Foo()
{
// Should these smart pointers be released? Or will falling out of scope/deletion release the memory?
myUPtr.release();
mySPtr.reset();
}
private:
std::unique_ptr<int> myUPtr;
std::shared_ptr<int> mySPtr;
};
int main()
{
// When each of the below variables fall out of scope is there any difference in memory release?
Foo f;
std::unique_ptr<Foo> uFoo(new Foo);
std::shared_ptr<Foo> sFoo(new Foo);
std::unique_ptr<int> uPtr(new int);
std::shared_ptr<int> sPtr(new int);
// Will all these smart pointers be released automatically?
// No need to call .release()/.reset() on any member and non-member smart pointers?
return 0;
}
您是否仍需要释放/重置它们以确保释放内存?
没有
还是可以让它们超出范围?
是
析构函数应该始终释放这些变量吗?
没有
使智能指针如此智能和强大的原因之一是,您不再需要担心手动管理内存。
仅供参考, std::unique_ptr::release
实际上将减轻智能指针的职责:它返回原始指针,然后您需要对其进行手动管理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.