将std::vector分配给堆上特定内存位置的正确语法

Proper syntax to assign std::vector to a specific memory location on the heap?

本文关键字:位置 内存 语法 vector std 分配      更新时间:2023-10-16

我正试图在这两个SO帖子中实现关于将容器分配到堆上特定内存位置的方向:

  1. 将c++对象,特别是stl容器移动到特定的内存位置
  2. 在预分配内存中创建对象

然而,我一定是做了一些愚蠢的事情(我是c++的新手),因为我甚至不能让我的代码编译(使用c++ 11,你可以看到下面):

  std::vector<int> ints1 = {10, 20, 30};
  ints1.reserve(20);
  auto adr = &(*ints1.end());
  auto *ints2 = new(adr)(std::vector<int>(20);

我得到最后一行expected , or ; before )的错误,我认为这意味着我的语法是错误的,但是如何?

还有,一旦我修正了这个语法,确保这些对象确实是连续的最好方法是什么?我想我应该确保

&(*ints1.begin()) - &(*ints2.begin) is roughly on the order of sizeof(std::vector<int> v(20));

有更好的方法吗?

(注。我确实意识到我应该分配我将要使用的内存来避免未定义行为)

看起来你在;之前遗漏了a)。应该像这样

 auto *ints2 = new(adr)(std::vector<int>(20));