search

Home  >  Q&A  >  body text

c++ - 能否帮忙解释一下placement new的原型

void operator new( size_t, void *p ) throw() { return p; }

这是我查到关于placement new的原型,size_t为什么在“new(&str1) std::string("abc");”中没有体现?为什么直接return p就可以了,是因为这个函数并没有写完全(只是原型)吗?

天蓬老师天蓬老师2767 days ago607

reply all(1)I'll reply

  • 黄舟

    黄舟2017-04-17 15:41:48

    First of all, what you find is not the declaration of placement new, but the declaration of operator placement new. These operators are declared in the header file new.

    Regarding operator placement new, the C++11 standard has the following conventions:

    18.6.1.3.1 These functions are reserved, a C++ program may not define functions that displace the versions in the Standard C++ library (17.6.4). The provisions of (3.7.4) do not apply to these reserved placement forms of operator new and operator delete.

    In short, these operator placement new are of no use for the time being.

    Then, the expression new(&str1) std::string("abc") does not call the declaration you found (but this expression does call operator placement new internally). The calling method of operator placement new is: ::operator new(size, pointer);.


    There are two kinds of new in C++, one is called new expression and the other is called operator new. The former will call the latter to complete memory allocation and then construct the object. Operator new is defined in the header file new. If the program does not include this header file, the compiler will automatically generate a set of operator new.

    In other words, placement new expression and new expression will internally call operator placement new and operator new respectively. The former does not currently do "any work", and the latter "should" apply for a storage area. (Usually a class overloads operator new, which is the latter of the overload)

    reply
    0
  • Cancelreply