What is “Best Practice” For Comparing Two Instances of a Reference Type?

Implementing equality in .NET correctly, efficiently and without code duplication is hard. Specifically, for reference types with value semantics (i.e. immutable types that treat equvialence as equality), you should implement the System.IEquatable<T> interface, and you should implement all the different operations (Equals, GetHashCode and ==, !=). As an example, here’s a class implementing value equality: … Read more

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

Making operator

The problem with this setup is that the operator<< you defined above is a free function, which can’t be virtual (it has no receiver object). In order to make the function virtual, it must be defined as a member of some class, which is problematic here because if you define operator<< as a member of … Read more

Why doesn’t `std::initializer_list` provide a subscript operator?

According to Bjarne Stroustrup in Section 17.3.4.2 (p. 497) of The C++ Programming Language, 4th Edition: Unfortunately, initializer_list doesn’t provide subscripting. No further reason is given. My guess is that it’s one of these reasons: it’s an omission, or because the initializer_list class is implemented with an array and you’d have to do bounds checking … Read more

Why can overloaded operators not be defined as static members of a class?

Because there isn’t an obvious syntax to call such an operator, which would mean we’d have to make up something. Consider the following variables: X x1; X x2; Now, let’s pretend for a moment that we’re using normal member functions instead of operators – let’s say I changed operator+ to plus in your example. Each … Read more