有没有办法确定指向const的指针是否指向const对象?
bool is_const_object(const int* p) {
return ???;
}
int main() {
int x = 42;
const int y = 43;
assert(!is_const_object(&x));
assert(is_const_object(&y));
}
const_cast
通常是设计上的问题,只应在“紧急情况”下使用:通常你不知道结果是否真正可变。 - Asteroids With Wings
p
的类型是一个推导的模板参数,你可以使用std::is_const
来判断提供的参数是否为指向常量的指针。在is_const_object(&x)
和is_const_object(&y)
的情况下,你会得到正确的结果,但它不能告诉你指向对象的const
性质在所有情况下都是什么。 - François Andrieuxis_const_object
的指针类型是不是“指向常量的指针”,那很容易确定。但如果你想知道所指对象最初是否被声明为 const,这是不可能的。考虑以下代码:int x = 42; const int* p = &x;
在这种情况下,你会期望is_const_object(p)
返回什么? - Igor Tandetnik