目前我想知道如何正確使用std::unique_ptr
作爲const正確性的成員變量。const使用std :: unique_ptr/std :: shared_ptr正確組合
下面的例子允許改變由my_foo
所擁有的內容,儘管正在常量:
#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'嗎?基於這個名字,不應該被允許在這種情況下被調用 – UnholySheep
我想象的類似於你用原始指針做什麼。某種包裝類。 – juanchopanza
似乎是[std :: experimental :: propagate_const](http://en.cppreference.com/w/cpp/experimental/propagate_const)的用途。但是我沒有足夠的知識來寫答案。 –