【问题标题】:What is the difference between applying of `operator new(std::size_t);` and `new-expression`? [duplicate]应用`operator new(std::size_t);`和`new-expression`有什么区别? [复制]
【发布时间】:2014-07-12 12:42:22
【问题描述】:

我想了解operator new(std::size_t)new-expression 之间的所有区别。

#include <iostream>
#include <new>

using std::cout;

struct A
{
    int a;
    char b;
    A(){ cout << "A\n"; a = 5; b = 'a'; } 
    ~A(){ cout << "~A\n"; }
};

A *a = (A*)operator new(sizeof(A)); //allocates 8 bytes and return void*
A *b = new A(); //allocates 8 bytes, invoke a default constructor and return A*

您能否提供它们之间的所有差异?它们的工作方式不同吗?

【问题讨论】:

    标签: c++


    【解决方案1】:

    new-expression 分配所需的内存为新分配的对象调用相应的构造函数(给定参数)。

    new(std::size_t) operator 只是分配内存。

    阅读更多http://www.cplusplus.com/reference/new/operator%20new/

    【讨论】:

      【解决方案2】:

      new 表达式调用分配函数operator new。分配函数获取内存,new 表达式将内存转换为对象(通过构造它们)。

      所以下面的代码:

      T * p = new T(1, true, 'x');
      delete p;
      

      等价于以下操作序列:

      void * addr = operator new(sizeof(T));   // allocation
      
      T * p = new (addr) T(1, true, 'x');      // construction
      
      p->~T();                                 // destruction
      
      operator delete(addr);                   // deallocation
      

      请注意,您总是需要一个 new 表达式来创建对象(即调用构造函数)——构造函数没有名称,不能直接调用。在这种情况下,我们使用默认的placement-new 表达式,它除了创建对象之外什么都不做,不像non-placement 形式,它同时进行内存分配和对象构造。

      【讨论】:

      • c++spec 是这么说的吗?
      • @St.Antario:有点,是的。当然,还有一些细节,例如new T 对于分配函数和 T 构造函数中的异常都是原子的...
      • 您能否改进您的问题以提供参考?
      • @St.Antario:一元表达式,第 5 条...
      • @St.Antario 这是整个第 5.3.4 节 [expr.new]。 (delete 为 5.3.5)
      猜你喜欢
      • 2012-12-29
      • 1970-01-01
      • 2018-08-02
      • 1970-01-01
      • 2011-11-22
      • 2014-02-10
      • 2012-04-14
      • 1970-01-01
      相关资源
      最近更新 更多