c++ - 新(3)是什么意思?

标签 c++ memory-management operator-overloading new-operator

SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);

这里的new操作符是什么意思?

new运算符后面的数字3是什么意思?

最佳答案

此代码来自 LLVM's codebase . 有一个自定义 operator new in scope它被用于placement-new初始化对象(参见 placement syntax)

void *User::operator new(size_t Size, unsigned Us) {
  return allocateFixedOperandUser(Size, Us, 0);
}

这是一个玩具示例:

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;
}

Live Example

具体来说,该代码用于调整分配的空间以适应其他数据。

关于c++ - 新(3)是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43753974/

相关文章:

c++ - 运算符重载 : Simple Addition. .. 错误 C2677:二进制 '+':未找到具有类型 ___ 的全局运算符(或没有可接受的转换)

c++ - 如何从派生类中的基类调用运算符?

c++ - 使用 C 字符串时出错

c++ - GMock 的 `WillOnce` 和 `Return` 不会因错误的返回值而失败

c++ - C++中delete和delete[]的区别

Java反射和OOM错误

C++ operator+ 的简单重载不编译

c++ - 使用 openssl/md5 的意外 MD5 哈希值

c++ - 有符号字节和奇偶校验字节的区别

c - Malloc 没有分配我告诉它的那么多内存(我相信)