【发布时间】:2013-06-09 08:45:37
【问题描述】:
我试图了解何时是使用 boost 附带的一些结构的合适时间,并且对 boost::optional 的使用有疑问并提供参考。
假设我有以下课程,使用boost::optional:
class MyClass {
public:
MyClass() {}
initialise(Helper& helper) {
this->helper = helper;
}
boost::optional<Helper&> getHelper() {
return helper;
}
private:
boost::optional<Helper&> helper;
}
我为什么要使用上面的而不是:
class MyClass {
public:
MyClass() : helper(nullptr) {}
initialise(Helper& helper) {
this->helper = &helper;
}
Helper* getHelper() {
return helper;
}
private:
Helper* helper;
}
它们都传达了相同的意图,即getHelper 可以返回null,调用者仍然需要测试是否返回了帮助器。
如果您需要知道“a value”、nullptr 和“not a value”之间的区别,您是否应该只使用boost::optional?
【问题讨论】:
-
boost::optional
只是 T* 的包装。比 boost::optional 更喜欢 T*,因为 boost::optional 在 C++ 中很奇怪。 T* 具有更好的可读性
标签: c++ boost boost-optional