【发布时间】:2015-02-26 00:55:51
【问题描述】:
假设我有一个像这样的简单类
class Foo
{
public:
void foo()const
{
str[5] = 'x';
obj->changeTheWorld();
x = 4;
y.get() = 5;
obj2->changeTheWorld();
}
private:
char *str; //some referenced data, not owned by Foo
ComplexObj *obj; //some referenced data, not owned by Foo
int &x; //references as well
//wrapped reference, but has a "T& get()const"
std::reference_wrapper<int> y;
//an occasionally useful pointer wrapper for complex memory cases
//but has a "T* get()const"
std::shared_ptr<ComplexObj> obj2;
};
这是有效的,因为在 const 方法中,它只是指针本身变成了 const,而不是它指向的数据。但是在许多情况下,这不是我想要的,如果 const 方法试图更改这些成员的内容(直接或通过在该成员上调用非 const 方法),我希望出现编译错误。
有标准的解决方案吗?
我认为某种包装类应该能够实现这一点,并且也应该是编译器优化出来的东西,尽管还没有坐下来尝试设计这样的东西来涵盖所有情况,比如strong_const<char*> str和strong_const<int&>(也不确定一个好名字......)。
【问题讨论】:
-
有一个C++17的提案,propagate_const.
-
std::string会按照你想要的方式行事。不知道为什么引用会编译,这对我来说似乎是错误的。 -
@MarkRansom 类可以有引用成员。 (它使隐式生成的构造函数为
deleted) -
显示了一些非字符案例。我的意图是永远不会将其视为字符串,就像类型外部的东西而不是它所拥有的东西(所以不能是值类型,因为这是一个副本,并且 unique_ptr、shared_ptr 等具有与原始指针相同的 const 行为) .
标签: c++ c++11 constants const-correctness