gpt4 book ai didi

C++:为我的类型定义了我自己的赋值运算符,现在 .sort() 不会对我的类型的 vector 起作用?

转载 作者:太空狗 更新时间:2023-10-29 23:47:37 24 4
gpt4 key购买 nike

我有一个类(读过 Accelerated C++ 的人可能会觉得这个类很熟悉)定义如下:

class Student_info{
public:
Student_info() : midterm(0.0), final(0.0) {};
Student_info(std::istream& is){read(is);};

Student_info(const Student_info& s);

~Student_info();

Student_info& operator=(const Student_info& s);

//Getters, setters, and other member functions ommited for brevity

static int assignCount;
static int copyCount;
static int destroyCount;

private:
std::string name;
double midterm;
double final;
double finalGrade;
std::vector<double> homework;

};

typedef std::vector<Student_info> stuContainer;


bool compare(const Student_info& x, const Student_info& y);

函数 calculator() 使用这种类型的对象。作为函数的一部分,(已声明的)Student_info 对象的 vector 使用库的通用排序函数进行排序。我的程序没有超过这一点(尽管根据 NetBeans 没有抛出异常并且程序正确退出)。

排序函数大量使用容器中保存的任何类型的赋值运算符,但我似乎无法找出我定义的那个有什么问题(程序在我定义它之前运行正常)。根据 Accelerated C++(或者至少我是这样解释的),赋值运算符应该工作的正确方法是首先销毁左操作数,然后用等于右操作数的值再次构造它。所以这是我重载的 operator= 定义:

Student_info& Student_info::operator=(const Student_info& s)
{
if(this != &s)
{
this->~Student_info();
destroyCount++;

*this = s;
}

return *this;
}

如您所见,它调用了 Student_info 复制构造函数,其定义如下:

Student_info::Student_info(const Student_info& s)
{
name = s.name;
midterm = s.midterm;
final = s.final;
finalGrade = s.finalGrade;
homework = s.homework;

copyCount++;
}

复制构造函数正确运行,因为省略排序语句允许程序正确运行并产生大于 0 的 copyCount(仅在复制构造函数和 operator= 中修改)。

那么我的赋值运算符究竟有什么问题呢?它与调用 Student_info 对象的销毁有关,但我不知道如何在不销毁它的情况下纠正它。

(顺便说一句,Accelerated C++ 中的练习要求创建复制构造函数、析构函数和赋值运算符...我意识到这些函数的综合版本显然足以满足我的类(class))

最佳答案

不,不,不。它根本不应该那样工作。您当前的赋值运算符会销毁它所调用的对象,然后在销毁的对象(哦,嘿,未定义的行为)上调用自身(哦,嘿,无限递归)。您不应该销毁现有对象。完全没有。并且此代码 *this = s 根本不调用任何构造函数,它调用赋值运算符 - 这就是您刚刚定义的。复制构造函数调用看起来像 new (this) Student_info(s);。这是一个已知的模式,它在很多很多方面都很糟糕。如果你有一本推荐它的书,把它扔进垃圾箱

赋值运算符应该将数据从右侧复制到左侧。在大多数情况下,最简单的方法就是复制每个数据成员。该运算符的语义不涉及破坏任何东西。任何使用此运算符的人都有权期望不会破坏任何 Student_info 对象。

只需调用成员现有的赋值运算符,然后实现您需要的任何附加逻辑。

关于C++:为我的类型定义了我自己的赋值运算符,现在 .sort() 不会对我的类型的 vector 起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4806827/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com