Jonas Jonas - 21 days ago 5
C++ Question

Why does a const_cast (or static_cast) not add const?

I was looking at this answer and wanted to use. However, I get a

Segmentation fault
, when using the
static_cast
and
const_cast
, but if I use a temp variable everything is fine. It is obviously because the non-const version of
bar()
calls it self over-and-over. But I though the
static_cast
would result in a
const foo*
and then choose the const version of
bar()
. Why is that so?

#include <iostream>
using namespace std;

class foo
{
public:
void bar() const
{
cout << "const" << endl;
}

void bar()
{
cout << "non-const" << endl;

// static_cast<const decltype(this)>(this)->bar();

// const_cast<const decltype(this)>(this)->bar();

const auto& tmp = *this;
tmp.bar();
}
};

int main() {
foo A;
A.bar();
const foo B;
B.bar();
static_cast<const foo*>(&A)->bar();
return 0;
}


Update:
I have confirmed the behaviour using the following compilers:


  • Debian clang version 3.5.0-10

  • g++ (Debian 4.9.2-10)

  • g++ 5.1 (ideone.com)


Answer

decltype(this) is foo*. And const decltype(this) is foo* const.

You don't change the pointees cv-qualifications, only the pointers. Therefore the non-const overload is chosen every time.