Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you ever make operator `new` private?

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.

like image 253
The Quantum Physicist Avatar asked Feb 02 '17 09:02

The Quantum Physicist


People also ask

What is the role of new operators?

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 do we overload new operator in C++?

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.

What does the new operator do in C++?

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?

What type of class member is operator new? Explanation: static is a type of class member is operator new.


1 Answers

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:

  • http://www.stroustrup.com/JSF-AV-rules.pdf
  • http://www.qa-systems.com/tools/qa-misra/
like image 99
Bruno Martin Avatar answered Oct 01 '22 23:10

Bruno Martin