Note that there are some explanatory texts on larger screens.

plurals
  1. POCustom object bad behaviour after std::sort
    text
    copied!<p>I'm experiencing issues after sorting a std::vector of Elevator, a custom class.</p> <p><strong>Class definition:</strong></p> <pre><code>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 &amp;other); ~Elevator(); char *ToCString(); bool operator&lt;(const Elevator&amp; rhs) const; static vector&lt;Elevator&gt; *ElevatorsFromWorkbook(const char *path); }; </code></pre> <p><strong>The less operator</strong> is implemented like this:</p> <pre><code>bool Elevator::operator&lt;(const Elevator&amp; rhs) const { return (this-&gt;m_id &lt; rhs.m_id); } </code></pre> <p><strong>ToCString</strong> method is implemented like this:</p> <pre><code>char *Elevator::ToCString() { char *output = (char*)malloc(sizeof(char) * (8+strlen(m_channel))); char type = 'U'; if (m_type == ELEVATOR_TYPE_A) { type = 'A'; } else if (m_type == ELEVATOR_TYPE_G) { type = 'G'; } else if (m_type == ELEVATOR_TYPE_M) { type = 'M'; } sprintf(output,"%d %s %c",m_id,m_channel,type); return output; } </code></pre> <p><strong>Copy constructor:</strong></p> <pre><code>Elevator::Elevator(const Elevator &amp;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; } </code></pre> <p>Example of the issue:</p> <pre><code>std::vector&lt;Elevator&gt; 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" </code></pre> <p>What am I doing wrong? Thanks for your time!</p> <p><strong>Note on compiling:</strong> I'm using Cygwin with these flags: -Wall -Wextra -fno-exceptions -fno-rtti -march=pentium4 -O2 -fomit-frame-pointer -pipe</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload