Home  >  Q&A  >  body text

C++的STL中关于new的用法,求帮忙!

以下是STL源码中的一段:

template <class _T1>
inline void _Construct(_T1* __p) {
 new ((void*) __p) _T1();
}

平时看见的new,是类似这样的用法

 _T1 * __p;
 __p=new _T1;

new ((void*) __p) _T1();

__p=new _T1;
等同吗?
而_T1()中的()又有什么特别含义吗?希望有人能帮忙解答!

巴扎黑巴扎黑2715 days ago640

reply all(1)I'll reply

  • 高洛峰

    高洛峰2017-04-17 15:41:53

    new(p) T is placement new. Its function is to construct the object T on the storage area pointed to by p. Generally, new will first apply for a storage area, and then construct an object on the applied storage area.

    std::string str1;
    str1.~basic_string();
    std::string *str2 = new(&str1) std::string("abc");

    T() is value initialization and is not equivalent to T. The function is to initialize the object through the default constructor or 0-initialize the object according to the type T.

    int *p = new int();
    assert(*p==0);

    PS: I made a mistake before. int a(); will be parsed by the compiler into a function declaration instead of a variable declaration.

    reply
    0
  • Cancelreply