2 ms·
> Suppose S::make and take_ownership were secretly colluding, like this: std::unique_ptr<S> *global; std::unique_ptr<S> S::make() { st
by Thorrez 3y ago
> 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.
- bobbyi 3y agoThe 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.
- eru 3y agoAt least that's the modern day retro-active justification. The historical origins of undefined behaviour in eg the C standard are murkier.