Home > Enterprise >  State of underlying resource when a shared_ptr is created from the raw pointer?
State of underlying resource when a shared_ptr is created from the raw pointer?

Time:08-26

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.

CodePudding user response:

The paragraph is weirdly worded. If you remove this sentence:

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.

It's fine. Indeed, talking about what would happen if the callee creates a new shared_ptr is something of a non-sequitur in this context.

This sentence is intended to be a warning not to create a shared_ptr from random pointers you get passed as arguments. The new shared_ptr is "independent from the original," but the rest of the sentence would be better stated as "and both of them will try to destroy the underlying resource". It's not so much that it doesn't "control" it; it's that it doesn't do so correctly.

  • Related