【发布时间】:2018-03-06 01:54:47
【问题描述】:
目前我想知道如何正确使用std::unique_ptr 作为关于 const 正确性的成员变量。
以下示例允许更改 my_foo 拥有的内容,尽管它是 const:
#include <iostream>
#include <memory>
struct foo {
foo() : value_ptr_(std::make_unique<int>(3)) {}
void increment() const {
++(*value_ptr_);
}
int get_value() const {
return *value_ptr_;
}
std::unique_ptr<int> value_ptr_;
};
int main() {
const foo my_foo;
std::cout << my_foo.get_value() << std::endl;
my_foo.increment(); // But my_foo is const!
std::cout << my_foo.get_value() << std::endl;
}
乍一看,将std::make_unique<T> 替换为std::make_unique<const T> 似乎是一个不错的解决方案。但是,这不允许更改 my_foo 的内容,即使它是非常量的:
#include <iostream>
#include <memory>
struct foo {
foo() : value_ptr_(std::make_unique<int>(3)) {}
void increment() {
++(*value_ptr_);
}
int get_value() const {
return *value_ptr_;
}
std::unique_ptr<const int> value_ptr_;
};
int main() {
foo my_foo;
std::cout << my_foo.get_value() << std::endl;
my_foo.increment(); // compiler error
std::cout << my_foo.get_value() << std::endl;
}
在这个最小示例中拥有一个指向 int 的指针当然不是很有意义,但在实际代码中,unique_ptr 可以拥有一个指向多态的基类的指针,即我们无法实现的对象只需按值存储。
那么如何更好地处理这种情况呢?
【问题讨论】:
-
我不知道您为什么允许在
const foo对象上调用increment?根据名称,在这种情况下不应该被调用 -
我想与您使用原始指针所做的类似。某种包装类。
-
似乎是 std::experimental::propagate_const 的用途。但是我没有足够的知识来写答案。
-
@UnholySheep 对我来说问题是,我首先被允许使用
const说明符写increment。 -
@NickyC,是的,看起来
std::experimental::propagate_const正是我要找的。似乎我必须等待相当长的时间才能使用它。 ;-)
标签: c++ pointers c++14 constants const-correctness