1

I am trying to implement the directions in these two SO posts regarding assigning containers to specific memory locations on the heap:

  1. Moving C++ objects, especially stl containers, to a specific memory location
  2. Create objects in pre-allocated memory

However, I must be doing something stupid (I'm new to C++) because I can't even get my code to compile (using C++ 11 as you can see below):

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

I am getting an error of a expected , or ; before ) for the last line, which I take to mean that my syntax is just wrong, but how?

Also, once I fix this syntax, what's the best way to ensure these objects really are contiguous? I thought I would ensure that

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

Is there a better way?

(p.s. I do realize I should allocate the memory I am going to use to do this to avoid undefined behavior)

Community
  • 1
  • 1
helloB
  • 3,472
  • 10
  • 40
  • 87
  • 2
    Creating a *vector* at a specific memory location will not affect where its data is stored because internally it contains only a pointer to its data. – Galik Jul 30 '15 at 20:38
  • Why do you want to have two different `std::vector` variables contiguous? `std::vector` already guarantees that elements are allocated in contiguous memory. – Antonio Pérez Jul 30 '15 at 20:38
  • 3
    If this is remotely intended to manage *elements* in a predefined area of memory, this code isn't even close. You need a custom *allocator* as the first linked question indicates. – WhozCraig Jul 30 '15 at 20:40
  • 1
    `ints1.end()` may be a singular value, not necessarily a past-the-end pointer. You should use `&ints1[0] + 3` or something. – M.M Jul 30 '15 at 21:35

1 Answers1

2

Looks like you're missing a ) before ;. Should look like this

 auto *ints2 = new(adr)(std::vector<int>(20));
blasko
  • 690
  • 4
  • 8