C++在指定内存构造对象

问题

为了提高程序的性能,一个做法是一次性分配足够多的内存,从而避免多次申请以及数据拷贝。对于c++,有一个问题:如何在已分配好的内存上构造对象?

前文“vector的性能利器:reserve”提到使用reserve预先分配内存,再push_backemplace_back,存储过万个大对象时可极大提升效率。探究其实现原理,会发现分配内存简单,调用标准库或者nedmalloctcmalloc等库中的函数即可;有了内存,问题同样变成如何在已分配的内存上构造对象?

方案

有两种解决方案解决这个问题。

placement new

第一种方案是使用placement new。其用法过程为:首先分配足够大的内存;然后用placement new语法生成对象:new(ptr) xxx(),其中ptr是足够容纳所指对象的指针。

一个使用例子:

class Person {
private:
  int age;
  std::string name;
public:
  // methods
};

int main(int argc, char** argv) {

  char mem[sizeof(Person)]; // 或者 auto mem = malloc(sizeof(Person));

  auto p = new(mem) Person();

  assert((void*)p == (void*)mem); // 两个指针指向同一块内存

  return 0;
}

使用placement new有三个注意点:一是要有足够的内存放置对象,这是必须的;二是指针应该是“对齐”的,例如对于4字节对齐的系统,指针地址应该是4的整数倍;三是你(可能)需要显式调用析构函数完成对象的销毁。

operator new

使用new生成对象实际上执行了三个操作:

  1. 调用operator new分配内存
  2. 调用类的构造函数
  3. 返回指针

其中operator new是可重载的,无论全局还是特定类。其函数原型为:

void* operator new(size_t sz);

回到把对象在指定内存上构造的问题上,我们可以通过重载operator new,返回已分配内存的指针。然而由于operator new函数只接受一个参数,地址指针需要是“全局”变量才能生效。这样想来,这种方案实用性并不高。

其他

如果你希望像vector中的reserve先分配内存,然后在其上装载对象,可以使用allocatorallocator定义在头文件中,能对指定类型分配合适的内存,并可手动调用对象的构造函数和析构函数。

用法示例:

int main(int argc, char** argv) {
  std::allocator<Person> alloc;
  auto p = alloc.allocate(1); // 分配一个Person对象的内存
  alloc.construct(p);   // 调用Person的构造函数,如果构造函数有参数,参数写在p之后
  // p 现在是一个指向Person的指针,且其指向对象被初始化过
  // 对p进行一些操作

  // 销毁对象,但不释放内存,等同于调用p->~Person()
  alloc.destroy(p);
  // 释放内存
  alloc.deallocate(p, 1);
  return 0;
}

对于可以内部管理的情形,建议使用allocator而非placement new

作用

为什么有这个需求呢?个人觉得有三方面的原因:

  1. 像vector的reserve,预先分配内存可大幅提高性能;
  2. 重复利用已分配好的空间,避免内存碎片;
  3. 细粒度进行内存管理,例如能够实现许多虚拟机中的将内存数据从一个片区转移到另一个片区(垃圾回收时触发)。

参考

  1. https://stackoverflow.com/questions/519808/call-a-constructor-on-a-already-allocated-memory
  2. https://isocpp.org/wiki/faq/dtors#placement-new
留言评论

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

Captcha Code

WordPress数据库错误: [Table 'ssrvps.vps_autoblog_queue' doesn't exist]
select * from vps_autoblog_queue where is_running >0

WordPress数据库错误: [Table 'ssrvps.vps_autoblog_queue' doesn't exist]
select count(*) from vps_autoblog_queue where task_id=6 and is_running>0

WordPress数据库错误: [Table 'ssrvps.vps_autoblog_queue' doesn't exist]
select id,fetched,is_running,last_date_time from vps_autoblog_queue where task_id=6 and source_url_key='85f8e27ce55bd78fd33f47d2b1409198'

WordPress数据库错误: [Table 'ssrvps.vps_autoblog_queue' doesn't exist]
insert into vps_autoblog_queue(task_id,source_url,source_url_key,create_date_time,not_check_stoped,post_interval) values(6,'https://www.hijk.pw/post-sitemap.xml','85f8e27ce55bd78fd33f47d2b1409198',1750367967,0,0)

WordPress数据库错误: [Table 'ssrvps.vps_autoblog_queue' doesn't exist]
select count(*) from vps_autoblog_queue where task_id=4 and is_running>0

WordPress数据库错误: [Table 'ssrvps.vps_autoblog_queue' doesn't exist]
select id,fetched,is_running,last_date_time from vps_autoblog_queue where task_id=4 and source_url_key='54b1dccf98c13c81f546faf82132bc77'

WordPress数据库错误: [Table 'ssrvps.vps_autoblog_queue' doesn't exist]
insert into vps_autoblog_queue(task_id,source_url,source_url_key,create_date_time,not_check_stoped,post_interval) values(4,'https://ssr.tools/sitemap-posttype-post.2020.xml','54b1dccf98c13c81f546faf82132bc77',1750367967,0,0)

WordPress数据库错误: [Table 'ssrvps.vps_autoblog_queue' doesn't exist]
select count(*) from vps_autoblog_queue where task_id=2 and is_running>0

WordPress数据库错误: [Table 'ssrvps.vps_autoblog_queue' doesn't exist]
select id,fetched,is_running,last_date_time from vps_autoblog_queue where task_id=2 and source_url_key='91372ddcd9e4809b115feaa5b6f00815'

WordPress数据库错误: [Table 'ssrvps.vps_autoblog_queue' doesn't exist]
insert into vps_autoblog_queue(task_id,source_url,source_url_key,create_date_time,not_check_stoped,post_interval) values(2,'https://tlanyan.me/post-sitemap.xml','91372ddcd9e4809b115feaa5b6f00815',1750367967,0,0)

WordPress数据库错误: [Table 'ssrvps.vps_autoblog_queue' doesn't exist]
select count(*) from vps_autoblog_queue where task_id=7 and is_running>0

WordPress数据库错误: [Table 'ssrvps.vps_autoblog_queue' doesn't exist]
select id,fetched,is_running,last_date_time from vps_autoblog_queue where task_id=7 and source_url_key='569e17863f7693f1afa9e9256af9dcff'

WordPress数据库错误: [Table 'ssrvps.vps_autoblog_queue' doesn't exist]
insert into vps_autoblog_queue(task_id,source_url,source_url_key,create_date_time,not_check_stoped,post_interval) values(7,'https://aisoa.cn/sitemap.xml','569e17863f7693f1afa9e9256af9dcff',1750367967,0,0)

WordPress数据库错误: [Table 'ssrvps.vps_autoblog_queue' doesn't exist]
select count(*) from vps_autoblog_queue where task_id=9 and is_running>0

WordPress数据库错误: [Table 'ssrvps.vps_autoblog_queue' doesn't exist]
select id,fetched,is_running,last_date_time from vps_autoblog_queue where task_id=9 and source_url_key='cc9416f8df40d8c3a48e66856b1cd6fd'

WordPress数据库错误: [Table 'ssrvps.vps_autoblog_queue' doesn't exist]
insert into vps_autoblog_queue(task_id,source_url,source_url_key,create_date_time,not_check_stoped,post_interval) values(9,'https://www.v2rayssr.com/sitemap.xml','cc9416f8df40d8c3a48e66856b1cd6fd',1750367967,0,0)

WordPress数据库错误: [Table 'ssrvps.vps_autoblog_queue' doesn't exist]
select count(*) from vps_autoblog_queue where task_id=10 and is_running>0

WordPress数据库错误: [Table 'ssrvps.vps_autoblog_queue' doesn't exist]
select id,fetched,is_running,last_date_time from vps_autoblog_queue where task_id=10 and source_url_key='74714f67855820f0c701ce905b231f27'

WordPress数据库错误: [Table 'ssrvps.vps_autoblog_queue' doesn't exist]
insert into vps_autoblog_queue(task_id,source_url,source_url_key,create_date_time,not_check_stoped,post_interval) values(10,'https://doubibackup.com/sitemap.xml','74714f67855820f0c701ce905b231f27',1750367967,0,0)

WordPress数据库错误: [Table 'ssrvps.vps_autoblog_queue' doesn't exist]
select id,is_running,last_post_time,post_interval,not_check_stoped from vps_autoblog_queue WHERE is_running>0 and fetched=0 order BY id ASC

WordPress数据库错误: [Table 'ssrvps.vps_autoblog_queue' doesn't exist]
select id,sn_id from vps_autoblog_queue WHERE is_running=0 and fetched=0 order BY id ASC LIMIT 1