+ 2

How to stop heap memory allocation for class in case of make_shared

Hi Refer code below: https://code.sololearn.com/cUe01sBygcuy Observed that I have overloaded operator new inside class and upon code execution, I am getting custom allocation cout statement once only for raw pointer, that is clsTest* p I dont get custom allocation for make_shared i.e. for sp1. I wanted to make this overloaded new operator private so that we can stop memory allocation on heap for class. but doing so, I am able to allocate memory on heap using make_shared as it is not calling class overloaded new operator. Is there a way to do so? P.S. : If i have class without any operator overloading of new and with new operator overloaded at global level, make_shared and raw pointer both allocates memory from global operator overloaded.

6th Apr 2022, 11:20 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
1 Answer
+ 1
To stop heap memory allocation for class in case of make_shared, you can use the std::allocate_shared function instead of std::make_shared. The std::allocate_shared function takes an allocator as its first argument, and the allocator will be used to allocate the memory for the object. This means that you can use a custom allocator to allocate the memory on the stack instead of the heap. For example, the following code shows how to use std::allocate_shared to allocate a clsTest object on the stack: #include <iostream> #include <memory> using namespace std; class clsTest { public: clsTest() { cout << "Constructor\n"; } ~clsTest() { cout << "Destructor\n"; } }; int main() { { // Allocate a `clsTest` object on the stack. shared_ptr<clsTest> sp1 = allocate_shared<clsTest>(); } return 0; } Note that the std::allocate_shared function is not part of the C++ standard library. It is part of the C++11 TR (Technical Report), which is a draft of the C++11 standard. However, most compilers support the std::allocate_shared function.
30th May 2023, 9:47 AM
Sameer Mistry
Sameer Mistry - avatar