This link about shared pointers states that
You can pass a shared_ptr to another function in the following ways: ... Pass the underlying pointer or a reference to the underlying object. This enables the callee to use the object, but doesn't enable it to share ownership or extend the lifetime. If the callee creates a shared_ptr from the raw pointer, the new shared_ptr is independent from the original, and doesn't control the underlying resource. Use this option when the contract between the caller and callee clearly specifies that the caller retains ownership of the shared_ptr lifetime.
Similar case which uses raw pointers to show better practice of initializing shared pointers using make_shared
and new
clearly states that if initialization from raw pointers occurs, it would cause to deletion of the resource twice.
I am also trying to run code below:
void f(int* ptr)
{
shared_ptr<int> sptr(ptr);
cout << "sptr in f: " << sptr.get() << endl;
}
int main()
{
auto sp1 = make_shared<int>(1);
cout << "sp1 in main: " << sp1.get() << endl;
f(sp1.get());
return 0;
}
and get following error.
sp1 in main: 0x6000016f5138
sptr in f: 0x6000016f5138
a.out(12083,0x119097600) malloc: *** error for object 0x6000016f5138: pointer being freed was not allocated
a.out(12083,0x119097600) malloc: *** set a breakpoint in malloc_error_break to debug
zsh: abort ./a.out
My question is what is meant in the given link by
If the callee creates a shared_ptr from the raw pointer, the new shared_ptr is independent from the original, and doesn't control the underlying resource.
when it is not the case from my example code output and also similar stack overflow post link above.