Hacker News new | past | comments | ask | show | jobs | submit login

> 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.




The usual justification for having a concept of "undefined behavior" at all is specifically to allow compilers to "rule out this possibility" so they can make this sort of optimization.


At least that's the modern day retro-active justification. The historical origins of undefined behaviour in eg the C standard are murkier.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: