隐<T>式转换为 T* 的"making" unique_ptr陷阱?
Pitfalls of "making" unique_ptr<T> implicitly convertible to T*?
我刚看完
添加从unique_ptr
关注的是如何做的部分,而不是我应该做的部分。我也不是问你是否认为这是一个好主意,但我要求具体的陷阱,我可能会碰到,或进入,如果我子类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
相关文章:
- 为什么 std::unique 不调用 std::sort?
- 生成"unique"矩阵
- 我对 std::unique(算法)C++有问题
- std::shared_ptr::unique(),复制和线程安全
- 如何在C++03中用自定义谓词调用std::unique
- 解决方法:'can not be used when making a shared object; recompile with -fPIC'使用Cmake。使用普通的 g++ 工作
- C++ std::unique并没有显示我对它的期望
- C++14 unique_ptr并使用已删除的函数'std::unique-ptr' unique_ptr错误
- C++ 如何生成 10,000 个 UNIQUE 随机整数以存储在 BST 中?
- Making use of max_element?
- C++:'unique vector'数据结构
- 为什么 [std::unique] 不能应用于 [std::multiset]?
- 使用 std::unique 和 vector.erase 删除除最后一次出现的重复元素之外的所有元素
- making boost work (visual studio 2010 windows 2007)
- 是否可以在 std::unique<T[ ]> 上应用 std::sort?
- 使用C++代码在Windows Phone 8.1中获取Unique DeviceId
- unique()似乎正在添加最后一个元素的另一个副本
- 如何使用"unique"从矢量中删除重复项?
- std::unique 是否有大小限制
- making tree with unordered_map