0

I'm currently learning the STL and finding something I cant understand in the placement new;

placement new put a temporary varieable into a allocated memory.

But the life of temporary clearly says that the temporary varieable should be died after the line;

Why is that work?

    // construct method to set value into some already allocated
    template <class T, class T2>
    inline void construct(T* pointer, T2& value)
    {
        new(pointer) T(value);
    }
  • 2
    "placement new put a temporary varieable into a allocated memory" - that assertion is wrong. All this does is construct a copy of `value` into the memory pointed to by `pointer`. There is nothing 'temporary' here to expire. (well, besides the return result of the placement-new expression, but that's just `pointer`). – WhozCraig Mar 09 '23 at 05:16
  • @WhozCraig isn't T(value) is to creat a temporary varieable? – KEIFTH YANG Mar 09 '23 at 05:19
  • 2
    For a similar reason to why `new T(value)` doesn't create a temporary `T` object – Artyer Mar 09 '23 at 05:24
  • @Artyer sorry I totally lost, I originally think the temporary object is created without name, and the life scope is so short, as long as run after the line they die. If I ject new a object without name it, isn't it a temporary object? – KEIFTH YANG Mar 09 '23 at 05:42
  • Non-placement `new` creates objects whose lifetimes extend until they are `delete`d. – molbdnilo Mar 09 '23 at 08:57
  • `T(value)` only creates a temporary when it is a *postfix-expression*, not when it is part of a *new-expression*. Subtle detail of the C++ grammar. – Chris Dodd Mar 09 '23 at 20:25

0 Answers0