【发布时间】:2019-04-05 10:46:28
【问题描述】:
我们有很多使用原始指针的现有代码,这些代码几乎在每次使用时都充满了空检查。
在尝试更简洁地编写更新的代码时,我们尝试使用工厂构造方法和 unique_ptrs。
我的问题是,在下面的代码中,一旦我们获得了工厂创建的对象 - sensorX - 我们是否可以在其余代码中使用它而无需对其进行进一步的空检查,因为它是一个 const unique_ptr?
DeviceFactory.h
class DeviceFactory
{
public:
template<typename T>
static unique_ptr<T> create(int id, std::string status)
{
auto device = unique_ptr<T>{ new T{ id, status } };
if (!device) throw DeviceCreationException("device couldn't be created");
return device;
}
};
用法
const auto sensorX = DeviceFactory::create<Sensor>(123, "sensorX");
【问题讨论】:
-
使用
std::make_unique -
然后写你自己的
your_cool_namespace::make_unique。您的功能与make_unique相同(只有if (!device)是多余的,它不能为空,导致new抛出)。无需重新发明轮子。 How to implement make-unique in C++11. -
(a) OP 不能使用
make_unique所以他们自己写。 (b) 贡献者谴责 OP 没有使用make_unique。 (c) OP 指出他们不能使用make_unique。 (d) 贡献者指示 OP 自己编写。 (你无法弥补!) -
如果你觉得你的代码有比它应该有的更多的空检查,这里是 Herb Sutter 关于指针、智能指针、引用和参数传递的一些指导。 herbsutter.com/2013/06/05/…
-
@Eljay,感谢 Herb Sutter 链接 - 我们显然会将这些要点用于相关场景。
标签: c++ c++11 unique-ptr