目前我在思考如何正确地使用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<const T>
替换std::make_unique<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
可能会持有指向多态对象的基类指针,即我们无法通过简单存储值来存储的对象。
那么如何更好地处理这种情况呢?
std::experimental::propagate_const
正是我要找的。不过似乎我得等一段时间才能使用它。;-) - Tobias Hermann