C++ 重载 new 知识总结

new 的基本职能

创建一个存在时间不被作用域所影响的 object。

步骤:

  1. 分配空间
  2. 初始化对象
  3. 返回空间

使用 new 的四种语法

  1. new (type ) new-initializer (optional)  
  2. new type new-initializer (optional)   
  3. new (placement-args ) (type ) new-initializer (optional) 
  4. new (placement-args ) type new-initializer (optional)  

组成介绍:

  1. type 比如 int, double
  2. new-initializer 大括号内的表达式, 用于指定初值, 如  new double[]{1, 2, 3};
  3. placement-args 额外的参数,在 type 之前, 如  new(2,f) T;

另一个 placement-args 的例子

重载 void* operator new(std::size_t size)

这个函数要负责空间的分配。

注意不需要负责初始化对象的工作。

例子:

#include <iostream>
class Foo {
public:
 void* operator new(std::size_t size)
 {
  std::cout << "operator new" << std::endl;
  return std::malloc(size);
 }
};

int main()
{
 Foo* m = new Foo;
 std::cout << sizeof(m) << std::endl;
 delete m;
 return 0; 
}

重载 void* operator new(std::size_t size, T otherarg)

是 new 重载的另一种形式, 这个函数不负责分配新的空间。

这种重载函数对应了 placement new。

它让我们可以在 new 时传入额外参数, 并进行一些操作。

#include <iostream>
class Foo {
public:
 void* operator new(std::size_t size, int num)
 {
  std::cout << "operator new" << std::endl;
  std::cout << "num is " << num << std::endl;
  return std::malloc(size);
 }
};

int main()
{
 Foo* m = new(100) Foo;
 std::cout << sizeof(m) << std::endl;
 delete m;
 return 0; 
}

开源项目中的例子

llvm 的 User.cpp 中重载了 new, 部分代码如下:

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

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

void *User::operator new(size_t Size) {
  // Allocate space for a single Use*
  void *Storage = ::operator new(Size + sizeof(Use *));
  Use **HungOffOperandList = static_cast<Use **>(Storage);
  User *Obj = reinterpret_cast<User *>(HungOffOperandList + 1);
  Obj->NumUserOperands = 0;
  Obj->HasHungOffUses = true;
  Obj->HasDescriptor = false;
  *HungOffOperandList = nullptr;
  return Obj;
}

参考

operator new, operator new[] - cppreference.com

new expression - cppreference.com

详解C++重载new, delete - 知乎

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值