Yip*_*Yay 7 c++ memory-leaks shared-ptr
我无法理解为什么以下代码会产生内存泄漏(我使用的boost::shared_ptr是静态类实例).有人能帮助我吗?
#include <crtdbg.h>
#include <boost/shared_ptr.hpp>
using boost::shared_ptr;
#define _CRTDBG_MAP_ALLOC
#define NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
static struct myclass {
static shared_ptr<int> ptr;
myclass() {
ptr = shared_ptr<int>(NEW int);
}
} myclass_instance;
shared_ptr<int> myclass::ptr;
int main() {
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF |
_CRTDBG_CHECK_ALWAYS_DF | _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Mic*_*ler 11
这是内存泄漏.您正在初始化名为myclass_instance的myclass的静态实例.您还在初始化"shared_ptr myclass :: ptr".
根据Stroustrup [3],静态按照它们被定义的顺序初始化.因此,您具有myclass_instance的静态定义,它在构造时初始化内部ptr.但是,您可以定义静态myclass :: ptr,它会调用shared_ptr的默认构造函数.
这是经典静态排序问题的一个例子.编译器认为myclass :: ptr实际上并未初始化,因此不会破坏原始的shared_ptr.相反,它只是泄露.
你需要某种裸指针.如果您正在使用C++ 11,则可以使用三元赋值语句执行Nifty Counter技术,如果您确定该对象已经初始化,则该语句会移动到自身.它非常粗糙,但它确实有效.
这是我在C++ 11中的表现:
#include <crtdbg.h>
#include <memory>
using std;
#define _CRTDBG_MAP_ALLOC
#define NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
// Note that the count could also be a field in an initializer static used in the Nifty Counter
// Technique covered in many texts.
static int count = 0; // This gets implicitly initialized to 0 by the executable load into memory.
static struct myclass {
static shared_ptr<int> ptr;
myclass() {
if (count++ == 0) {
ptr = make_shared<int>(0); //initialization
}
}
} myclass_instance;
shared_ptr<int> myclass::ptr = count == 0 ? make_shared<int>(0) : move(myclass::ptr);
int main() {
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF |
_CRTDBG_CHECK_ALWAYS_DF | _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅以下内容
小智 8
猜测CRT正在报告误报 - 以下代码说明共享指针正常工作,至少使用g ++
#include <iostream>
#include "boost/shared_ptr.hpp"
using namespace std;
using namespace boost;
struct R {
R() {
cerr << "ctor" << endl;
}
~R() {
cerr << "dtor" << endl;
}
};
struct A {
static shared_ptr<R> ptr;
A() {
ptr = shared_ptr<R>(new R);
}
};
shared_ptr<R> A::ptr;
static A a;
int main() {
}
Run Code Online (Sandbox Code Playgroud)
它打印:
ctor
dtor
Run Code Online (Sandbox Code Playgroud)