Comment

Comment by Thorrez

> Suppose S::make and take_ownership were secretly colluding, like this:

     std::unique_ptr<S> *global;
     
     std::unique_ptr<S> S::make() {
         std::unique_ptr<S> origp = std::make_unique<S>();
         global = &origp;
         return origp;
     }
     
     void take_ownership(S *rawp) {
         delete rawp;
         *global = std::make_unique<S>();
     }

>The compiler cannot rule out this possibility

Why can't the compiler rule out that possibility? That looks like undefined behavior code to me, so thus the compiler could rule it out. S::make() is storing a pointer to a local variable (origp), and then that pointer is being accessed after S::make() has returned. I'm pretty sure that's undefined behavior.

parent Thorrez 3 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton