开发者

operator overloading and the usage of const_cast

开发者 https://www.devze.com 2023-04-05 11:30 出处:网络
For the following code snippet, class A{ const int a; public: A(): a(0){} A(int m_a):a(m_a){}; A& operator =(const A &other);

For the following code snippet,

class A{
  const int a;
  public:
  A(): a(0){}
  A(int m_a):a(m_a){};
  A& operator =(const A &other);
};
A & A::operator =(const A &other)
{
  const_cast<int&>(a) = other开发者_StackOverflow中文版.a;
  return *this;
}

what do the lines of

A & A::operator =(const A &other)

const_cast<int&>(a) = other.a;

mean? Or why this operator is defined this way? In other words, I feel confused about its usage and the way it is defined/written.


The const_cast removes the const from the const member a, thus allowing the assignment from other.a to succeed (without the const_cast the type of a would be const int, and thus it wouldn't be modifiable).

Probably the idea is that a is initialized at class construction and can't be modified "by design" in any other place, but the author of the class decided to make an exception for assignment.

I have mixed feelings against this piece of code, very often the use of a const_cast is a symptom of bad design, on the other hand it can be logical to allow assignment but retain the const for all the other operations.


a is a const member variable. const_cast(a) bypasses the const-correctness rules. Otherwise, you could only assign a in the initializer list of the constructor.

0

精彩评论

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