简体   繁体   中英

Implicit conversion regarding constness in c++

#include <iostream>
int foo(const char* keke) {
  std::cout << keke;
  return 0;
}
int main()
{
  char* keke = new char(10);
  char* const haha = keke;
  return foo(haha);
}

Why there is no any errors/warning while compiling the above code?

The type of haha is char* const , while foo only receive argument of type const char* . Could char* const implicit convert to const char* ?

Yes. It's called qualification conversions (one of the implicit conversions):

(emphasis mine)

A prvalue of type pointer to cv-qualified type T can be converted to a prvalue pointer to a more cv-qualified same type T (in other words, constness and volatility can be added).

"More" cv-qualified means that

a pointer to unqualified type can be converted to a pointer to const;
...

It means char* could be implicitly converted to const char* .

const qualifier on the pointer itself doesn't matter here, the parameter keke itself is declared to be passed by value, it's fine the argument to be copied from haha (ie the const pointer; char* const ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM