绑定shared_from_this,内存不会被释放
bind shared_from_this the memory will not be released
#include <iostream>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/enable_shared_from_this.hpp>
class A: public boost::enable_shared_from_this<A>
{
typedef boost::function<int()> GET;
public:
A()
{
std::cout << "A::A() " << this << std::endl;
}
~A()
{
std::cout << "A::~A()" << this <<std::endl;
}
void set()
{
myget=boost::bind(&A::get, shared_from_this());
}
这里有一个问题:当我用shared_from_this()绑定它时,它不会被释放。但是如果我用this (boost::bind(&A::get, this))绑定它,实例将被释放。
int getI()
{
myget();
}
inline int get()
{
return 1;
}
private:
GET myget;
};
void test()
{
boost::shared_ptr<A> a(new A);
a->set();
a->getI();
}
int main()
{
test();
return 0;
}
我的问题是:为什么即使程序已经关闭,A的实例也永远不会被释放?
问题是myget
变量会阻止析构函数的运行。
所以你甚至不能写
~A() {
std::cout << "A::~A()" << this << std::endl;
myget = {};
}
这就是弱指针被发明的目的。在这种特殊情况下,您可以简单地使用this
,因为在A
myget
相关文章:
- 包含矢量指针的结构的内存释放问题
- Valgrind 声称内存释放中的自由空间太多
- 当 C 和 C++ 中严格要求内存释放时
- C++ 中指针变量的内存释放
- 德克内存释放
- 临时对象 c++ 的内存释放
- C 全局对象变量内存释放
- C++矢量动态内存释放/删除
- 从 cv::Mat 初始化的 IplImage 的内存释放
- SWIG类型映射中的内存释放
- STL容器中的内存释放
- QWebView内存释放
- 内存释放 C++
- 大返回值(如字符串)的内存释放如何在C++中发生
- 重新分配之前的内存释放
- Linux C++ 中的内存释放
- VS2012编译器奇怪的内存释放问题
- 调试断言失败!错误的内存释放
- 负责 COM 互操作中的内存释放
- imread命令后OpenCV矩阵内存释放