views:

187

answers:

2

Hello!

I can't understand why does the following code produce memory leaks (I am using boost::shared_ptr with static class instance). Could someone help me?

#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;
}
+7  A: 

Most likely the leak is detected before the global objects get destroyed and shared_ptr has a chance to release the object, so it's likely a false leak.

sharptooth
+4  A: 

At a guess the CRT is reporting a false positive - the following code illustrates that the shared pointer is working correctly, at least with 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() {
}

It prints:

ctor
dtor
anon
+1 for test code
neuro