我正在处理那些不是我写的代码。我有这样的声明:
// p is type of std::unique_ptr<uint8_t[]>
if (p < 0) { /* throw an exception */ }那么,在这种情况下,p < 0意味着什么呢?
在the documentation page上,我相信我的案例是16) y < nullptr,其中0是nullptr。
但是它能做什么呢?
发布于 2020-01-16 02:03:31
unique_ptr <0或者小于运算符做什么?
它与cppreference operator<(const unique_ptr&, nullptr_t);上的过载(11)匹配。0隐式转换为std::nullptr_t。根据文档,结果是std::less<unique_ptr<T,D>::pointer>()(x.get(), nullptr)。
结果是定义了实现,但可能在大多数系统上都是无条件错误的。假设在一个特殊的系统上,null没有0的二进制表示,结果可能是真的。
我相信我的情况是16)
(16)也是同样的方式:0 > unique_ptr。结果是一样的。
发布于 2020-01-16 03:46:38
检查operator <是否未在代码库中的某处重载。这似乎是(p < 0)成为true的唯一途径。
示例:
bool operator< (const std::unique_ptr<uint8_t[]>&, int) { return true; }
int main() {
std::unique_ptr<uint8_t[]> p;
std::cout << (p < 0) << std::endl;
}打印:
1live demo
否则,正如其他人所说,0隐式转换为std::nullptr_t,这将选择bool operator<(const unique_ptr<T, D>& x, nullptr_t)重载,这将调用返回false的std::less(p, 0) (即使在带有-1指针值的Windows上也是如此)。
发布于 2020-01-16 02:05:23
此表达式与this template operator (0正在转换为nullptr)匹配:
template <class T, class D>
bool operator<(const unique_ptr<T, D>& x, nullptr_t);这将返回std::less<unique_ptr<T,D>::pointer>()(p.get(), nullptr),它始终为false (因为std::less是一个严格的顺序函数器) (demo)。
https://stackoverflow.com/questions/59757034
复制相似问题