I read the smart pointer from C++ Primer 5 Edition. In section 12.1.3, some description goes like
The smart pointer types define a function named 'get' that returns a built-in pointer to the object that the smart pointer is managing. The function is intended for cases when we need to pass a built-in pointer to code that can't use a smart pointer. The code that uses the return from 'get' must not 'delete' that pointer.
A example is also given below the description
shared_ptr<int> p(new int(42)); // reference count is 1
int *q = p.get();
{//new block
//undefined:two independent shared_ptr point to the same memory
shared_ptr<int>(q);
}//block ends, q is destroyed ,and the memory to which q points is freed
int foo = *q; //undefined; the memory to which p points was freed
I can understand the explanation above clearly. BUT, when I come across Exercise 12.13, I am a little bit confused.
#include<iostream>
#include<memory>
using namespace std;
int main(){
auto sp = make_shared<int>();
auto p = sp.get();
delete p;
cout <<"Before main function exits!"<<endl; //which I add for debug
return 0;
}
There is no error in compiling. But an Error goes like below when running
***Error in './ex12_13': double free or corruption(out): 0x09b97018***
And the context to debug Before main function exits! has not been excuted, which means the error happens just after delete operation in my opinion. I also use 'gdb' the debug this program and error pops out just after delete indeed.
SO, how to explain the error? Delete freed the memory already but when does the second free happen? Before main function exits?
I changed the initialization of sp from make_shared function to new and use my own deleter function in place of delete.
#include<iostream>
#include<memory>
using namespace std;
int main(){
auto deleter = [](int*p){
cout<<"deleter called"<<endl; delete p;
};
shared_ptr<int> sp(new int, deleter);
auto p = sp.get();
delete p;
cout <<"Before main function exits!"<<endl; //which I add for debug
return 0;
}
Then the output turns out to be
Before main function exits!
deleter called
***Error in './ex12_13_2': double free or corruption(out): 0x08995998***
when the program goes out of main scope, the local variable shared_ptr p will be destroyed and the memory p points to will be deleted by calling deleter.
That's why the ”before main function exits!" shows firstly, the deleter called shows later and finally the double free error.
So I think the confusion I put forward above is mainly from make_shared. @Ben Voigt gives a detailed explanation.
You are deleting a pointer that didn't come from new, so you have undefined behavior (anything at all can happen).
But the underlying reason maybe could only be found from the implement of make_shared.