对我应该是简单的c ++代码有点麻烦。
我写了一个类来描述一个成员(作为一个社交媒体网络成员),一个成员有std ::关注者列表和std ::以下列表,都是类型成员*,他可以关注/取消关注其他成员。
以下是完整的课程:
Member.h
{
"id" : "1622745d8ee96a59",
"threadId" : "1622745d8ee96a59"
}
Member.cpp
class Member {
private:
bool isCopy;
static int counter;
int id;
list<Member*> following;
list<Member*> followers;
public:
Member();
Member(const Member &p2);
~Member();
void follow(Member &member);
void unfollow(Member &member);
int numFollowers();
int numFollowing();
static int count();
bool operator==(const Member &other) const;
bool operator!=(const Member &other) const;
};
这是一个简单的代码,导致我遇到一些问题:
int Member::counter = 0;
Member::Member()
{
counter++;
id = counter;
isCopy = false;
cout << "Constructor ID: " << id << endl;
}
Member::Member(const Member & p2)
{
this->id = p2.id;
isCopy = true;
}
Member::~Member()
{
cout << "Destructor ID: " << this->id << endl;
if (!isCopy)
{
counter--;
}
}
void Member::follow(Member &member)
{
if (find(following.begin(), following.end(), &member) == following.end())
{
following.push_back(&member);
member.followers.push_back(this);
}
}
void Member::unfollow(Member &member)
{
following.remove(&member);
member.followers.remove(this);
}
int Member::numFollowers()
{
return followers.size();
}
int Member::numFollowing()
{
return following.size();
}
int Member::count()
{
return counter;
}
bool Member::operator==(const Member & other) const
{
return this->id == other.id;
}
bool Member::operator!=(const Member & other) const
{
return this->id != other.id;
}
测试函数结束后我可以看到member3的析构函数被调用,但是在main函数中如果我看到member2的以下列表和member1的跟随者列表(两个类型成员*)仍然有指向member3地址,他有一些垃圾值:
Member member1, member2;
int main() {
test();
}
void test(){
Member member3;
member2.follow(member3);
member3.follow(member1);
}
我的目标是当member3的范围结束时,member2的以下列表的大小和member1的关注者列表的大小将为0。 有没有办法解决这个问题?
谢谢大家!
答案 0 :(得分:2)
当对象被销毁时,您需要清除this
和followers
中following
的链接。
像
这样的东西Member::~Member()
{
std::cout << "Destructor ID: " << id << std::endl;
if (!isCopy)
{
counter--;
}
std::for_each(followers.begin(), followers.end(), [this](Member * other){ other.following.remove(this); });
std::for_each(following.begin(), following.end(), [this](Member * other){ other.followers.remove(this); });
}