Shared_ptr with array | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Shared_ptr with array

Hi all Why p2 being int array is allocating same size as of int? Should it not allocate 24*5 = 120? https://code.sololearn.com/c0tdy0fXUAOb/?ref=app

26th Feb 2022, 4:03 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
4 Answers
+ 2
"std::make_shared ()" doesn't use your implementation of "new" operator to allocate the storage for the object, it instead uses global placement new operator ( which can't be overloaded ) The place where your "new" is being used is to allocate memory ( 24 in this case ) to store internals like shared_count. you can confirm this by making shared ptr for different types : https://code.sololearn.com/ca97KJFS2CKI/?ref=app -- some useful links :- 1. Placement new : https://en.cppreference.com/w/cpp/language/new#Placement_new 2. std::make_shared : https://en.cppreference.com/w/cpp/memory/shared_ptr/make_shared
27th Feb 2022, 6:06 AM
Arsenic
Arsenic - avatar
+ 2
Ketan Lalcheta yes, if you are working with C++20 ( or above ) make_shared<int[5]> (); or make_shared<int[]> (5); Should work as intended.
27th Feb 2022, 1:25 PM
Arsenic
Arsenic - avatar
+ 1
It's because in your environment, a pointer IS an integer. To actually allocate the memory, you would have to call ‘new int[5]’ I think they’re both pointers to an int. sizeof(int*) would be the same as sizeof(int**)
27th Feb 2022, 7:31 AM
A S Raghuvanshi
A S Raghuvanshi - avatar
0
Okay... So shared_ptr<int[]> p2 = make_shared<int[5]>(); Is proper to allocate array ?
27th Feb 2022, 12:35 PM
Ketan Lalcheta
Ketan Lalcheta - avatar