vendredi 26 octobre 2018

Understanding smart pointers but error: pointer being freed was not allocated

I am trying to understand smart pointers and have the following code:

 #include <iostream>
 #include <string>
 #include <memory>
 using namespace std;

 struct B 
 {
     string hello() { return "hello world"; }
 };

 class A
 {
 private:
     B* a;
 public:
     A() { a = new B; }
     ~A() { delete a; a = nullptr; }
     B* get() { return a; }
 };

 int main(int argc, const char * argv[]) {
     A a;
     shared_ptr<B> p(a.get());
     cout << p->hello() << endl;
     p.reset();
     return 0;
 }

What I am trying to do here, is access the raw pointer, but through the smart pointer. It prints "hello world" just fine, and there are no errors when I comment out the destructor for A. However, when I uncomment it, I get the following error:

 test(9758,0x7fff738d9300) malloc: *** error for object 0x1001053a0: pointer 
 being freed was not allocated
 *** set a breakpoint in malloc_error_break to debug

What is going on here? Is the shared_ptr, p, calling the destructor when it goes out of scope or resets (to nullptr)? How is p dealing with the memory leak from not deleting A::a?

I understand that smart pointers generally handle new objects and this is probably a case not used often, but I want to try to learn this.

Aucun commentaire:

Enregistrer un commentaire