Overwriting an object with an object of same type

后端 未结 2 1851
挽巷
挽巷 2020-12-11 20:19

Is the following well defined?

#include 
#include 

using namespace std;

struct Const {
    const int i; 
    Const (int i)          


        
2条回答
  •  爱一瞬间的悲伤
    2020-12-11 20:50

    This is only intended as an addendum to @Tony D's answer, regarding

    new (p) Const(2) erase the old object stored at p

    I think you need to differentiate between an object and the conceptual idea of an "instance".

    [...] An object is a region of storage.[...]

    [N4431 §1.8/1]

    So the pointer p points to a region of storage, which contains the bit pattern of some "instance" before the placement new and some different bit pattern of a different, but well constructed "instance" of the correct (same) type.

    So at the location pointed to by p there's a valid object, and when assigning q from it q points to it. Though as noted in the other answer, accessing it via p isn't permited.

提交回复
热议问题