这是创建一个不能改变它指向的值std::experimental::observer_ptr
的非对象的规范方法吗?const
auto i = int{0};
auto p = std::experimental::make_observer(&std::as_const(i));
*p = 1; // compilation error, as desired
编辑:
如果指针已经存在(我认为这是更常见的用例)怎么办?我们必须这样做const_cast
吗?
auto i = int{0};
auto p = &i;
auto q = std::experimental::make_observer(const_cast<const int*>(p));
*q = 1; // compilation error, as desired