Placement new breaks consts and references?

后端 未结 4 1906
攒了一身酷
攒了一身酷 2020-12-20 15:29

Following the discussion on my answer to this question, apparently:

the following code is allowed

struct Foo {
    int x;
};

Foo f;         


        
4条回答
  •  一生所求
    2020-12-20 16:16

    As far as I can tell, it's just a matter of semantic correctness, and the adherent assumptions that the optimizer may make. Consider this:

    Bar important, relevant;
    
    Foo x(important);  // binds as const-reference
    
    Zoo z(x);  // also binds as const reference
    
    do_stuff(z);
    
    x.~Foo();
    ::new (&x) Foo(relevant);  // Ouch?
    

    The object z may reasonably expect its Foo member reference to be constant and thus refer to important. As the standard says, the destruction plus new construction in the last two lines "automatically updates all references to refer to the (logically) new object", so now the const-reference inside z has changed, despite the promise of being constant.

    To avoid this backstabbing violation of const-correctness, the entire reconstruction-in-place is forbidden.

提交回复
热议问题