Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to idiomatically define assignment operator for immutable classes?

In C++ what is the idiomatic way to define operator= on a class that should be immutable. For example all its member variables are const.

typedef unsigned char byte;

class Binary
{
protected:
    const unsigned long size;
    const byte* bytes;

public:
    Binary(const unsigned long size);
    Binary(const Binary &b);
    ~Binary(void);

    Binary& operator=(const Binary &b);
};

where bytes is a pointer to a block of memory malloced at run time.

Do I define an empty assignment operator or let it use the automatically generated on which will obviously fail?

I am trying to implement and enforce single assignment semantics on a few select classes.


1 Answers

Assuming that you are not going to reassign your members (using const_cast etc.), I would suggest to explicitly mention in your code that you are not using operator =.

In Current C++ standard, make it private and unimplemented:

class Binary
{
  //...
private:
  Binary& operator = (const Binary&);
};

In upcoming C++0x standard, delete it:

class Binary
{
  //...
  Binary& operator = (const Binary&) = delete;
};
like image 128
iammilind Avatar answered Mar 15 '26 05:03

iammilind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!