为什么没有安全的选择unique_ptr :: operator *()? [英] Why is there no safe alternative to unique_ptr::operator*()?
问题描述
std :: vector
具有成员函数 at()
,作为 operator []
,以便应用绑定检查,并且不创建悬挂引用:
std::vector
has the member function at()
as a safe alternative to operator[]
, so that bound checking is applied and no dangling references are created:
void foo(std::vector<int> const&x)
{
const auto&a=x[0]; // what if x.empty()? undefined behaviour!
const auto&a=x.at(0); // throws exception of x.empty()
}
但是, std :: unique_ptr
缺少相应的功能:
However, std::unique_ptr
lacks the corresponding functionality:
void foo(std::unique_ptr<int> const&x)
{
const auto&a=*x; // what if bool(x)==false? undefined behaviour!
}
如果 std :: unique_ptr
有这样一个安全的选择,说成员 ref()
(和 cref()
)它从不返回悬挂引用,而是抛出异常。可能的实现:
It would be great, if std::unique_ptr
had such a safe alternative, say member ref()
(and cref()
) which never returns a dangling reference, but rather throws an exception. Possible implementation:
template<typename T>
typename add_lvalue_reference<T>::type
unique_ptr<T>::ref() const noexcept(false)
{
if(bool(*this)==false)
throw run_time_error("trying to de-refrence null unique_ptr");
return this->operator*();
}
有什么好的理由为什么标准不提供这种东西?
Is there any good reason why the standard doesn't provide this sort of thing?
推荐答案
我怀疑真正的答案很简单,同一个很多的为什么C ++不喜欢这样? 。问题:
I suspect the real answer is simple, and the same one for lots of "Why isn't C++ like this?" questions:
没有人提出。
std :: vector
和
std :: unique_ptr
不是由相同的人设计的,同时,并不是以相同的方式使用,所以不一定遵循相同的设计原则。
std::vector
and std::unique_ptr
are not designed by the same people, at the same time, and are not used in the same way, so don't necessarily follow the same design principles.
这篇关于为什么没有安全的选择unique_ptr :: operator *()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!