const 引用确保您无法更改所引用的对象。例如:
int i = 1;
const int& ref = i;
ref = 42; // error, because of a const reference
但是如果你使用对指针或unique_ptr
的引用, 你可以。示例:
class TinyClass {
public:
int var = 1;
void f1() { var = 42; }
};
std::unique_ptr<TinyClass> pointer(new TinyClass);
const std::unique_ptr<TinyClass>& constRef = pointer;
constRef->f1(); // no error
我假设发生这种情况是因为指针本身没有改变。但是这个感觉misleading
,或者像一个容易犯的错误。有没有一种简单的方法来声明对指针的“真实”const 引用?如:确保对象本身是常量。
编辑:假设我不能只更改 unique_ptr 的类型。一个真实的场景是一些对象是在 vector<unique_ptr<C>>
中构造的。并且某些函数获得对其元素之一的(常量)引用。
最佳答案
const
在 const std::unique_ptr<TinyClass>& constRef
保证 constRef
一旦建立,将不会指向另一个对象。它与对象本身无关。
如果你想防止改变对象本身:
std::unique_ptr<const TinyClass> ptr_to_const_object;
编辑(OP 编辑后):
你什么也做不了。因为有一个函数需要 const vector<unique_ptr<C>>&
,该函数清楚地告诉您它需要处理指针内的对象(甚至是指针),但它不需要更改 vector 项(例如添加新项或删除它)。
关于c++ - 对指针的 const 引用可以改变对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41278511/