2

I found this is working well but don't know if this is safe as I don't understand why it works:

struct X{ static X& make(){ return *std::make_shared<X>(); } ... } int main(){ const auto& a = X::make(); a.function(); ... // seems like the instance holds and nothing broken } 

In my understanding, the returned reference to the derefed object out of shared_ptr operator* should not impact how shared_ptr manages the instance's reference count: so the created instance inside make() should be destroyed after make() is done. But this pattern of code has been working well for many times and I don't see why. So I'm not sure if we can really do it in this way... appreciate any comments!

4
  • 6
    Undefined behavior is undefined. Commented Mar 24, 2019 at 19:01
  • 1
    "But this pattern of code has been working well for many times and I don't see why." - luck. Perhaps the memory you are referencing just happens to still contain the same data but it could be overwritten at any time. Commented Mar 24, 2019 at 19:24
  • 1
    Why not return the shared pointer? Commented Mar 24, 2019 at 19:53
  • Thanks Martin for asking, I was working on DSL API to chain a few ops in one statement, for example: – auto query = table("name").select(...).groupby(...).sortby(...).limit(10); I would like to avoid -> between these function calls, so I have choice to return object itself for table(), but the object may be destroyed soon after method chain, if I allow object copy for every call in the chain, I guess it should work. So I was looking ways if I can keep object ref type for every function but still keep the object, then I found above pattern working, and was looking for opinions on it. Commented Mar 25, 2019 at 5:12

1 Answer 1

8

No, the shared pointer returned from make_shared is instantly destroyed after the return and thus the reference obtained by dereferencing it will be dangling. It might look like it works but it really is just undefined behavior, and as said in the comments undefined is undefined.

Sign up to request clarification or add additional context in comments.

1 Comment

Indeed. An in case someone is not convinced, here the demo: ideone.com/e2tspU

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.