2015-12-15 72 views
1

我正在学习C++放置新的代码。C++ Placement new and构造函数调用

class Cell { 
    public: 
    Cell() { 
     printf("default constructor by %s\n", __func__); 
    } 
    Cell(int ina) : a(ina) { 
     printf("customized constructor.\n"); 
    } 
    ~Cell() {} 
    void* operator new(size_t);        // Operator new. 
    void* operator new(size_t, Cell*p) { 
     return p; 
    } 
    private: 
    int a;             // tmp variable. 
}; 

// Global variable. 
Cell global_cell; 

void* Cell::operator new(size_t size) { 
    printf("start running the placement new\n"); 
    Cell* ptr = new (&global_cell) Cell; 
    printf("the cell pointer is %p and the global address is %p\n", ptr, &global_cell); 
    return ptr; 
} 


int main() { 
    printf("====\n"); 
    Cell *ptr = new Cell; 
    printf("====\n"); 
} 

这是我得到的输出:

default constructor by Cell 
===== 
start running the placement new 
default constructor by Cell 
the cell pointer is 0x60107c and the global address is 0x60107c 
default constructor by Cell 
===== 

我所知道的第一个“默认构造函数”来源于global_cell开始。但为什么在那之后我得到了两个“默认构造函数”?我错过了关于展示位置的新内容吗?另外,我怎样才能实现与第二个非默认的构造函数接受一个输入整数的位置?

+0

对不起,这是一个错字,当我尝试手动编辑帖子。 – Jes

回答

0

您正在以错误的方式为班级实施自定义operator new

operator new对于一个类,应该只提供原始内存放置实例的位置,而不是创建对象。使用new来初始化一个对象(因为您没有指定任何参数,所以在您的案例中使用默认构造函数)。

如果您想使用新的布局和参数传递只写

new (memory_address) MyObject(arg1, arg2); 

,但请注意,使用放置新的排序是一个替代来定义自定义operator new为类。在后者只需调用正常的分配与

new MyObject(arg1, arg2); 

使用您的自定义的分配器(不过这应该只是提供足够和正确对齐的内存)。

+0

谢谢你的回答!我只知道我唯一要做的就是返回内存地址。 :) – Jes

2
new (&global_cell) Cell 

operator new超载是一个默认的建设,new Cellmain是其他。

operator new只能分配内存,不能构造对象;之后会自动调用相关的构造函数。

使用放置新的与非默认构造函数也不是很复杂:(也就是说,没有差异的“常规” new

new (&global_cell) Cell(2) 

0

你让他们当你调用“新小区”:

Cell *ptr = new Cell; 
Cell* ptr = new (&global_cell) Cell; 

运营商新后调用构造函数总是被称为

+0

我明白了。谢谢! – Jes