【发布时间】:2011-12-09 11:07:02
【问题描述】:
我有一个“sum”类,它包含两个对现有整数的引用(比如说)。我想创建一个深度复制整数的“复制”方法。由于智能指针,我认为我永远不必在我的代码中手动 delete 对象,但我必须在这个解决方案中。此外,对于如此微不足道的任务(我需要重复几节课)来说,它太复杂了。有没有更直接的解决方案?
注意:我不想为每个对象添加一个 bool 成员(标志)以确定是否必须删除整数(在我的情况下,它的开销并不比析构函数中的 std::set 检查开销更好)
#include <set>
struct sum {
const int &a, &b;
static std::set<const int*> allocated_ints;
sum(const int& a, const int&b): a(a), b(b) {}
sum copy() const {
sum res(*new const int(a), *new const int(b));
allocated_ints.insert(&res.a);
allocated_ints.insert(&res.b);
return res;
}
~sum() {
if (allocated_ints.count(&this->a)) {
delete &this->a;
delete &this->b;
allocated_ints.erase(&this->a);
allocated_ints.erase(&this->b);
}
}
};
std::set<const int*> sum::allocated_ints;
【问题讨论】:
-
你不应该删除这些引用。
-
@rafak:你的代码引用了
ints,这意味着它们被其他类“拥有”,你的类不应该删除它们。如果它们不被其他类“拥有”,那么您不应该通过引用来存储ints。 -
你在说什么智能指针?我在您的代码中看不到任何智能指针。 (引用不是智能指针,如果您是这样想的话。)
-
@John:我将我的用例作为对 Kerrek SB 答案的评论。从类中分配引用时,我需要删除引用。
-
@MooingDuck:int 最常由其他类拥有。在极少数情况下,它们不是(这就是我需要通过副本构建它们的原因)。
标签: c++ reference smart-pointers deep-copy