samedi 8 mai 2021

c++ - question on static_class explicit conversion and constness

I am reading C++ Primer 5Ed and i don't understand the below section.
Appreciate any help.

const char *cp;
// error: static_cast can't cast away const
char *q = static_cast<char*>(cp);

string s1 = static_cast<string>(cp); // No error: why is this ok? The constness is removed here but static_cast does not remove constness.

string s2 = static_cast<const string>(cp); // No error: why is this ok? Assigning const string to string does not seem right? Of course assigning a non const string to a const string is fine (??)

Aucun commentaire:

Enregistrer un commentaire