placement new on a class with reference field

前端 未结 2 456
礼貌的吻别
礼貌的吻别 2020-12-17 19:08

This is a code example from the C++20 spec ([basic.life]/8):

struct C {
  int i;
  void f();
  const C& operator=( const C& );
};

const C& C::o         


        
2条回答
  •  一个人的身影
    2020-12-17 19:48

    To answer the currently open questions:

    First question:

    • What is the case of such code in C++14 or before (when std::launder didn't exist)? Probably it is UB - this is why std::launder was brought to the game, right?

    Yes, it was UB. This is mentioned explicitly in the NB issues @Language Lawyer referred to:

    Because of that issue all the standard libraries have undefined behaviors in widely used types. The only way to fix that issue is to adjust the lifetime rules to auto-launder the placement new. (https://github.com/cplusplus/nbballot/issues/7)

    Second question:

    If in C++20 we do not need std::launder for such a case, how the compiler can understand that the reference is being manipulated without our help (i.e. without "Pointer optimization barrier") to avoid caching of the reference value?

    Compilers already know to not optimize object (or sub-object) value this way if a non-const member function was called between two usages of the object or if any function was called with the object as a parameter (passed by-ref), because this value may be changed by those functions. This change to the standard just added a few more cases where such optimization is illegal.

提交回复
热议问题