0

I just started using Smart Pointers in C++, and ran into some trouble, but can't figure out where I went wrong. I have a class Seat, and SeatSmart having pointer to Seat class. These are my classes:

class Seat{
  public:
     int val;
     int idx;
     Seat(int v, int i):val(v),idx(i){}
};

class SeatSmart{
  public:
     Seat *seat;
     SeatSmart():seat(NULL){}
     SeatSmart(Seat *st):seat(st){}
     ~SeatSmart(){
        delete(seat);
     }
}

After this I ran the following code in main:

priority_queue<SeatSmart> pq;
vector<SeatSmart> q;
SeatSmart sm;
for(int i = 0 ; i < 10 ; i++){
  sm.seat = new Seat(i, i);
  pq.push(sm);
  q.push_back(sm);
}

I also overloaded the < operator:

bool operator<(const SeatSmart &a, const SeatSmart &b){
  return a.seat->val < b.seat->val;
}

The problem arises after adding the second element in the priority queue, when the operator < is called. The system shows a segmentation fault at that point according to GDB.

The copy constructor should be called when adding sm to the vector and the priority queue. Can you please tell me where I went wrong.

Karthik Prakash
  • 153
  • 4
  • 11
  • 2
    Um, you aren't using any smart pointers in your code. – NathanOliver Jan 14 '20 at 15:57
  • 1
    Does this answer your question? [What is The Rule of Three?](https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three) (with respect to `SeatSmart`) – Richard Critten Jan 14 '20 at 15:58
  • 1
    You don't need all of that code to see the error: `int main() {SeatSmart s1; s1.seat = new Seat(0,0); SeatSmart s2 = s1; }` boom, you're dead. No vectors, no priority queues, just a simple copy made. – PaulMcKenzie Jan 14 '20 at 16:00
  • “The copy constructor should be called” - what copy constructor? You have not written one. And do be aware that you either need to do reference counting or make your `SeatSmart` move-only (non-copyable). You can read about why `std::auto_ptr` was a failure and how `std::unique_ptr` and `std::shared_ptr` work – alter_igel Jan 14 '20 at 16:00
  • Using smart pointers would *usually* imply using `std::unique_ptr`, `std::shared_ptr`, `std::weak_ptr` (or in some cases `boost::` equivalents). But you are not using *any* of those. – Jesper Juhl Jan 14 '20 at 16:01
  • Note that because your `SeatSmart::seat` is allowed to be null, your `operator<` will cause Undefined Behavior when dereferencing it – alter_igel Jan 14 '20 at 16:03

0 Answers0