【发布时间】:2017-12-21 09:28:38
【问题描述】:
采用这个虚拟结构:
struct foo
{
int* pI;
void bar() const
{
int* ptrToI = pI; // I want this to require 'const int*'
*ptrToI = 5; // I want this to fail
}
}__test__;
如何设计这个结构来防止我改变 pI 指向的值?
【问题讨论】:
-
const int* pI;?究竟是什么问题? -
与您的问题无关,但不要使用带有两个前导下划线的符号(例如
__test__),这些符号在所有范围内都是保留的。请看this old question and its answers for more information -
该解决方案被提议包含在C++标准中:propagate_const
-
如果您不需要
foo可分配,并且不需要重置pI所指的内容,那么从技术上讲,您可以使用 C++ 引用而不是 C++ 指针。否则,您可能会使用自定义智能指针,正如@lopital 在答案中所建议的那样。但很有可能您正在重新发明std::string或std::vector之类的东西,然后使用标准容器。