在看MINIBASE的源代码的时候发现里面有类似于这样的东西
bufTable = (BufDesc*) MINIBASE_SHMEM->malloc( numBuffers * sizeof(BufDesc) ); for ( unsigned index=0; index < numBuffers; ++index ) (void) new(bufTable+index) BufDesc;
没有见过这种new的用法,于是跑去查了一下,在这里找到了介绍。
参照这个原理写的小例子:
#include <iostream>
#include <cstdlib> using namespace std; class C { public: C(int _x) : x(_x) {} int x; }; int main(void) { C *ptr = (C *)malloc(sizeof(C)); (void) new(ptr) C(4); cout << ptr->x <<endl; return 0; }