0

Whether there are situations when the object needs to be created in memory to a certain address? Where it can be necessary (example)?

Thank you.

Lundin
  • 174,148
  • 38
  • 234
  • 367
Andrey Bushman
  • 10,992
  • 14
  • 77
  • 163
  • 3
    Implementing `std::vector`. (unless you mean exact values of addresses) – jrok Oct 04 '13 at 12:48
  • @LihO, I know about the `MyClass* x = new(ptr) MyClass(); // ptr is some pointer`variant. Where it can be need (samples)? – Andrey Bushman Oct 04 '13 at 12:52
  • A memory mapped file would be an example. – Hans Passant Oct 04 '13 at 12:55
  • @jrok, Can you explain yours answer? – Andrey Bushman Oct 04 '13 at 12:56
  • 1
    Situation: There are `n` objects of `T` inside a vector `v` and there's `m*sizeof(T)` memory reserved and `m > n` holds. If you do `push_back`, you need to construct an object at the exact address `&v[0]+n`. – jrok Oct 04 '13 at 13:01
  • I took the liberty to add the tag "Windows" to this question, since Visual C++ was mentioned. The answer depends a lot on what kind of system the program is running on. – Lundin Oct 04 '13 at 13:47

3 Answers3

0

You seem to be asking if in a C++ application it's ever necessary to construct an object at a specific address.

Normally, no. But there are exceptions, and the C++ language does support it.

One such exception is when building a kind of cache system for small objects in order to avoid frequent small allocations. One would first construct a large buffer, and then when the client code wants to construct a new small object, the caching system would construct it within this large buffer.

John Dibling
  • 97,027
  • 28
  • 181
  • 313
0

Take a look at placement new: " What uses are there for "placement new"? "

Good examples are writing your own memory allocator, garbage collector, or trying to precisely lay out memory due to cache performance.

It's a niche thing, but sometimes very useful.

Community
  • 1
  • 1
Paul Rubel
  • 25,810
  • 7
  • 57
  • 77
0

In C++, one may need to construct an object at a specific given address when implementing a pool allocator. For example, Boost Pool: http://www.boost.org/doc/libs/1_47_0/libs/pool/doc/index.html

John Zwinck
  • 223,042
  • 33
  • 293
  • 407