I'm using OpenSplice DDS, and there, almost all C++ classes (basic ones that I used, I can mention them if that matters) have overloaded new
operators to be private (to prevent users from using them). I don't understand, why would anyone do that? Could someone provide some examples that show the necessity of this?
Why I need new
: Because most of these classes don't have default constructors, and I need to initialize them later in my implementation through a unique_ptr
.
Easy trick: On the other hand... I can very easily trick this! I can just wrap this class with another class, and use new
all I want, right? Hence I don't understand the motivation and it feels like bad style. Could someone explain?
EDIT:
Just to clarify: Providing a good example where this can't be escaped is a good answer. It'll be helpful for all people who see new
operators made private.
The new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.
Why to overload new and delete? 1. The overloaded new operator function can accept arguments; therefore, a class can have multiple overloaded new operator functions. This gives the programmer more flexibility in customizing memory allocation for objects.
The new operator is an operator which denotes a request for memory allocation on the Heap. If sufficient memory is available, new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable.
What type of class member is operator new? Explanation: static is a type of class member is operator new.
Lots of embedded C++ need to guarantee that NO dynamic allocations are done once the system is started. The aeronautics, automotive and medical device industry often have this requirement. See the following links for such coding standards and the rational behind it:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With