Can a C++ constructor know whether it's constructing a const object?

203 Views Asked by At

In C++, object constructors cannot be const-qualified.

But - can the constructor of an object of class A know whether it's constructing a const A or a non-const A?

Motivated by a fine point in the discussion regarding this question.

1

There are 1 best solutions below

2
Davis Herring On

No, because copy elision (and the so-called guaranteed copy elision) can change the constness of an object "after" construction:

struct A {
  bool c;
  A() : c(magic_i_am_const()) {}
  A(const A&)=delete;      // immovable
};

const A f() {return {};}
A g() {return f();}        // OK
void h() {
  A x=f();                 // OK
  const A y=g();           // OK
}

What should x.c and y.c be?