隐<T>式转换为 T* 的"making" unique_ptr陷阱?

Pitfalls of "making" unique_ptr<T> implicitly convertible to T*?

本文关键字:unique making ptr 陷阱 gt lt 转换      更新时间:2023-10-16

我刚看完

添加从unique_ptrT *

关注的是如何做的部分,而不是我应该做的部分。我也不是问你是否认为这是一个好主意,但我要求具体的陷阱,我可能会碰到,或进入,如果我子类unique_ptr添加隐式转换的功能到一个原始指针(所以我可以直接传递它给函数接受指针,不使用get())。

考虑这个稍微做作的例子:

X* px;
{
    unique_ptr<X> ux = new X;
    px = ux; // implicit conversion
}
px->method();

当这样呈现时,很明显,对px->方法的调用将失败(或者不失败,这将更糟),但如果这段代码更复杂(例如调用以X*作为参数的方法),则可能无法捕获隐藏的错误。

例如将px = ux替换为调用functionWithMemory(ux);

void functionWithMemory(X * px)
{
   static X* oldX = nullptr;
   if(oldX)
   {
      oldX->goodbye();
   }
   px->hello();
   oldX = px;
}

仍然是人造的,但是如果你继续扩展它,它开始变得合理。

隐式转换将允许各种无意义的内容:

{
    unique_ptr<int> p(new int);
    p + 10; // OK with implicit conversion
    p[3];   // ditto
    bool x = p; // ditto
    unique_ptr<Derived> d(new Derived);
    unique_ptr<Base> b(d); // OK with implicit conversion...oops
                           // These two unique_ptr's own the same object!
}    // double deletion here