Joh*_*ith 17 c++ memory-management operator-overloading new-operator
SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
Run Code Online (Sandbox Code Playgroud)
new这里运营商的意义是什么?
操作员号码3后的数字是什么意思new?
Mar*_* A. 12
此代码来自LLVM的代码库.operator new 范围内有自定义,它用于放置 -初始化对象(cfr.放置语法)
void *User::operator new(size_t Size, unsigned Us) {
return allocateFixedOperandUser(Size, Us, 0);
}
Run Code Online (Sandbox Code Playgroud)
这是一个玩具示例:
class SelectInst
{
public:
int x;
};
void *operator new(size_t Size, unsigned Us) {
^^^^^^^^^^^ 3 is passed here
^^^^^^^^^^^ allocation size requested
return ... // Allocates enough space for Size and for Us uses
}
SelectInst *Create() {
return new(3) SelectInst();
}
int main()
{
auto ptr = Create();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
具体而言,该代码用于调整分配的空间以适应其他数据.
假设SelectInst提供了一个用户定义的贴图运算符new,它接受一个int用户定义的参数; 调用语法意味着使用该用户定义的放置operator new来进行内存分配.例如
class SelectInst {
public:
static void* operator new (std::size_t count, int args) {
// ~~~~~~~~
...
}
};
SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
// ~~~
Run Code Online (Sandbox Code Playgroud)