C++ std::sort之后的自定义对象错误行为
在对自定义类电梯的std::vector进行排序后,我遇到了一些问题 类定义:C++ std::sort之后的自定义对象错误行为,c++,C++,在对自定义类电梯的std::vector进行排序后,我遇到了一些问题 类定义: class Elevator { private: uint16_t m_id; char *m_channel; ElevatorType m_type; public: Elevator(uint16_t id, const char *channel, ElevatorType type); Elevator(const El
class Elevator
{
private:
uint16_t m_id;
char *m_channel;
ElevatorType m_type;
public:
Elevator(uint16_t id, const char *channel, ElevatorType type);
Elevator(const Elevator &other);
~Elevator();
char *ToCString();
bool operator<(const Elevator& rhs) const;
static vector<Elevator> *ElevatorsFromWorkbook(const char *path);
};
Elevator::Elevator(const Elevator &other)
{
m_id = other.m_id;
m_channel = (char*)malloc(sizeof(char)*(strlen(other.m_channel)+1));
strcpy(m_channel,other.m_channel);
m_type = other.m_type;
}
复制构造函数:
class Elevator
{
private:
uint16_t m_id;
char *m_channel;
ElevatorType m_type;
public:
Elevator(uint16_t id, const char *channel, ElevatorType type);
Elevator(const Elevator &other);
~Elevator();
char *ToCString();
bool operator<(const Elevator& rhs) const;
static vector<Elevator> *ElevatorsFromWorkbook(const char *path);
};
Elevator::Elevator(const Elevator &other)
{
m_id = other.m_id;
m_channel = (char*)malloc(sizeof(char)*(strlen(other.m_channel)+1));
strcpy(m_channel,other.m_channel);
m_type = other.m_type;
}
问题的例子:
std::vector<Elevator> elevators;
elevators.push_back(Elevator(4569,"CHANNEL3",ELEVATOR_TYPE_G));
elevators.push_back(Elevator(4567,"CHANNEL3",ELEVATOR_TYPE_G));
printf("%s\n",elevators.at(0).ToCString()); //Prints "4567 CHANNEL1 G"
std::sort(elevators.begin(),elevators.end());
printf("%s\n",elevators.at(0).ToCString()); //ISSUE: Prints "4567 4567 ▒#a G"
std::矢量电梯;
电梯。后推(电梯(4569,“通道3”,电梯类型);
电梯。后推(电梯(4567,“通道3”,电梯类型);
printf(“%s\n”,电梯.at(0.ToCString())//打印“4567 CHANNEL1 G”
std::sort(电梯.begin(),电梯.end());
printf(“%s\n”,电梯.at(0.ToCString())//问题:打印“45674567”▒#G“
我做错了什么?谢谢你的时间
编译注意事项:我正在使用带有以下标志的Cygwin:
-Wall-Wextra-fno exceptions-fno rtti-march=pentium4-O2-fomit frame pointer-pipe根据标准,
std::sort
要求对象是可交换的,这意味着可以对其调用swap
。由于您没有交换
重载,这意味着std::swap
。和std::swap
说
要求:T型应为可移动式(表20)和可移动式(表22)
(这是C++11。对于C++03,将“移动”替换为“复制”。)
您的类是不可复制分配的,因为它缺少
操作符=
重载,所以您应该添加它。(请参阅)注意,复制构造可以从默认构造合成,而且操作符=
看起来就像使用原始指针管理内存时遇到的那种麻烦(我建议使用std::string
而不是裸字符*`)。您的复制构造函数是如何定义的?尝试将所有char*
替换为std::string
,printf
替换为std::cout
,混合使用C/C++,悲惨的生活开始很可能是内存分配和其他东西弄乱了。尝试使用std::string
,您可能会看到这些问题vanish@Zi0P4tch0:您现在还需要一个赋值运算符,请参阅。或像大家推荐的那样使用std::string,并放弃赋值运算符和复制构造函数。当然,假设ElevatorType是可复制和可分配的。这样做可以使用编译器生成的构造和赋值代码(更不用说减少许多潜在的错误)。