开发者

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.


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;
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜