‘ auto const’和‘ const auto’是一样的吗?

auto constconst auto在语义上有区别吗? 还是它们的意思是一样的?

23275 次浏览

The const qualifier applies to the type to the immediate left unless there is nothing to the left then it applies to the type to the immediate right. So yup it's the same.

Contrived example:

std::vector<char*> test;
const auto a = test[0];
*a = 'c';
a = 0; // does not compile
auto const b = test[1];
*b = 'c';
b = 0; // does not compile

Both a and b have type char* const. Don't think you can simply "insert" the type instead of the keyword auto (here: const char* a)! The const keyword will apply to the whole type that auto matches (here: char*).