C++ static classes & shared_ptr memory leaks

后端 未结 3 895
执念已碎
执念已碎 2021-01-12 00:19

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?



        
3条回答
  •  盖世英雄少女心
    2021-01-12 00:32

    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 
    #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 ptr;
    
        A() {
         ptr =  shared_ptr(new R);
        }
    
    };
    
    shared_ptr A::ptr;
    static A a;
    
    int main() {
    }
    

    It prints:

    ctor
    dtor
    

提交回复
热议问题