【发布时间】:2013-12-24 05:12:18
【问题描述】:
在下面的代码中,我希望断言通过,但它没有。
这与documented behavior of unique_ptr::reset 不同,我觉得这很令人惊讶。
我做错了什么还是一个错误?这是一个问题,因为如果相同的元素被删除一次增益,析构函数会被调用两次。
#include <set>
#include <memory>
struct F
: std::enable_shared_from_this<F>
{
static int destructor_count;
static std::set<std::shared_ptr<F>> container;
F() {}
~F() {
assert(container.size() == 0);
container.clear(); // This will delete the same pointer twice.
destructor_count--;
}
};
int F::destructor_count = 0;
std::set<std::shared_ptr<F>> F::container;
int main()
{
F::container.insert(std::shared_ptr<F>(new F));
F::container.clear();
return 0;
}
编译器信息:
libstdc++6-4.6-dev
g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
Copyright (C) 2011 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
【问题讨论】:
-
旁注:使用
std::make_shared。 -
@chris 省去冗长的篇幅?
-
就是这样,但有时也有异常安全性。例如,如果
f占用其中两个,f(new A(), new B())可能会导致泄漏。 -
嗯...有趣。我没有意识到这一点。