Return value of placement new

后端 未结 2 426
挽巷
挽巷 2021-02-05 03:11

Consider the following C++14 code:

#include 
#include 
#include 

struct NonStandardLayout
{
    // ...
};

int main         


        
相关标签:
2条回答
  • 2021-02-05 03:45

    18.6.1.3 Placement forms [new.delete.placement]

    void* operator new(std::size_t size, void* ptr) noexcept;

    Returns: ptr.

    It is unambiguously specified that the placement new operator returns whatever pointer is passed to it. "Returns: ptr". Can't get any clearer than that.

    That, pretty much, seals the deal for me as far as "the return value from placement new" goes: placement new does nothing to the pointer it places, and it always returns the same pointer.

    Everything else in your question relates to any other changes that might occur as the result of the other casts; but you're asking specifically about the return value from placement new, so I take it that you're accepting that all other conversion are type-conversions only, and have no effect on the actual pointer, and you were only asking about placement new -- but it would also be possible to go through the other casts, and make a similar determination.

    0 讨论(0)
  • 2021-02-05 03:49

    I'm surprised no one has mentioned this cheap counterexample yet:

    struct foo {
      static foo f;
      // might seem dubious but doesn't violate anything
      void* operator new(size_t, void* p) {return &f;}
    };
    

    Demo on Coliru.

    Unless a class-specific placement version is called, however, your assertion should hold. Both expressions have to represent the same address as explained in the other answer (the main point being that the standard non-allocating operator new simply returns the pointer argument and the new expression not doing anything fancy), and neither of these is a pointer past the end of some object so, by [expr.eq]/2, they compare equal.

    0 讨论(0)
提交回复
热议问题