How do I prevent a class from being allocated via the ‘new’ operator? (I’d like to ensure my RAII class is always allocated on the stack.)

All you need to do is declare the class’ new operator private: class X { private: // Prevent heap allocation void * operator new (size_t); void * operator new[] (size_t); void operator delete (void *); void operator delete[] (void*); // … // The rest of the implementation for X // … }; Making ‘operator new’ … Read more

How to write C++ getters and setters

There are two distinct forms of “properties” that turn up in the standard library, which I will categorise as “Identity oriented” and “Value oriented”. Which you choose depends on how the system should interact with Foo. Neither is “more correct”. Identity oriented class Foo { X x_; public: X & x() { return x_; } … Read more