make_shared will make a single memory allocation dynamically and hence improves the performance . But how does it make a single memory allocation using new for both managed object and control block .I wanted to know how memory allocation actually happens internally .
Asked
Active
Viewed 1,075 times
0
-
There's no such guarantee. That's just a recommendation. – Kerrek SB Oct 12 '16 at 18:25
-
What's the question? Someone internally will call `::operator new` to allocate memory. – Kerrek SB Oct 12 '16 at 18:26
-
I agree , but doing new for manager object and again new for controller will allocate memory at different locations in heap . It will not be a single memory allocation . – user2717079 Oct 12 '16 at 18:30
-
3It can just allocate raw memory for `sizeof(controller)` + `sizeof(object)` + padding and then use placement `new` to initialize – Slava Oct 12 '16 at 18:31
1 Answers
2
make_shared will make a single memory allocation dynamically
Note that this is not required by the standard. It is possible, and good implementations do that.
How could it be done?
For example, it could be implemented by allocating an uninitialized block of memory that is large enough to contain both the control block and the pointed object taking their alignment requirement into account, then construct each of the two objects using placement new. std::malloc
may be used to allocate the memory. This is somewhat similar to how std::vector::reserve
can allocate a block of memory where multiple objects can later be constructed.

eerorika
- 232,697
- 12
- 197
- 326
-
Isn't it possible to create a `struct` that contains both the control block and pointed object, rather than using a raw block of memory? – Mark Ransom Oct 12 '16 at 19:21
-
@MarkRansom perhaps. I'm not confident enough to deny feasibility of such approach. It would certainly make the implementation simpler. If I were to implement the standard library, I would investigate that option first. – eerorika Oct 12 '16 at 19:34
-
The object passed to `make_shared` will need to be copied either way. – Mark Ransom Oct 12 '16 at 19:45
-
@MarkRansom when user allocates the object separately, they would be calling `shared_ptr::shared_ptr(Y*)` rather than `make_shared`, wouldn't they? That said, I removed my previous rambling. I really don't know if a struct is an option. – eerorika Oct 12 '16 at 19:48
-
I found an attempt at implementing `make_shared` [here on stackoverflow](http://stackoverflow.com/questions/27377868/make-shared-own-implementation) with a fine answer by Jonathan Wakely that fixes many problems of the original. That approach does use a struct. – eerorika Oct 12 '16 at 19:59