Can class with const members be assigned or copied

61 Views Asked by At

According to abseil.io/tips/177, it said

Specifically, if your class has const members, it cannot be assigned to (whether by copy-assignment or move-assignment). The language understands this: if your type has a const member, copy-assignment and move-assignment operators will not be synthesized.

I created a short snippet, I saw objects can be copied/moved. How could I understand that statement from abseil.io/tips/177?

#include <iostream>
class Stitch {
 public:
  Stitch(int in):num(in) { std::cout << "c'tor, address:" << this << std::endl; }
  ~Stitch() { std::cout << "d'tor, address:" << this << std::endl; }
  const int num;
  const std::size_t kAddr = (int)(this);
};
int main() {
  Stitch s1(1);
  std::cout << "s1 address: " << &s1 << " " << s1.num << std::endl;
  Stitch s2 = s1;
  std::cout << "s2 address: " << &s2 << " " << s2.num <<  std::endl;
  Stitch s3 = std::move(s1);
  std::cout << "s3 address: " << &s3 << " " << s3.num <<  std::endl;
  Stitch s4 = Stitch(4);
  std::cout << "s4 address: " << &s4 << " " << s4.num <<  std::endl;
}

1

There are 1 best solutions below

1
user12002570 On

How could I understand that statement

The statement talks about assignment and not initialization. They are different things. In particular, Stitch s2 = s1; is copy initialization and not copy assignment. So since Stitch s2 = s1; is copy initialization, the copy constructor can be used.

The important thing to here is that, the object is not const during construction otherwise the constructor won't be able to initialize the object as all of its data member would be const.

On the other hand, s2 = s1; is copy assignment which is what the quoted statement talks about.