Operator porównania - błąd naruszenia pamięci

0

Witam.
Mam problem z poniższym programem - zwraca błąd naruszenia pamięci.
Problem dotyczy operatora porównania.

Ma ktoś pomysł jak poprawić ten program?

#include <iostream>

struct A1
{
  A1() : x(0), y(0) {}
  A1(int x, int y)
  {
    this->x = x;
    this->y = y;
  }

  int x;
  int y;
};

class FirstClass
{
  A1* a1;

  public:
  FirstClass()
    : a1(nullptr) {}

  FirstClass(int x, int y)
  {
    a1 = new A1(x, y);
  }
  ~FirstClass()
  {
    delete a1;
  }

  int operator==(const FirstClass& rhs)
  {
    return (a1->x == rhs.a1->x && a1->y == rhs.a1->y);
  }

  FirstClass& operator=(const FirstClass& rhs)
  {
    if (this != &rhs)
    {
      delete a1;
      a1 = nullptr;
      a1 = new A1(rhs.a1->x, rhs.a1->y);
    }
    return *this;
  }
};


class SecondClass
{
  FirstClass firstClass;
  public:
  SecondClass() {}
  ~SecondClass() {};
  
  void run(const FirstClass& firtsClass)
  {
    if (this->firstClass == firstClass)
    {
      std::cout << "The same !" << std::endl;
      return;
    }
    else
      std::cout << "Different !" << std::endl;

    this->firstClass = firstClass;
  }
};

int main()
{
  FirstClass firstClass(1, 2);

  SecondClass secondClass;
  secondClass.run(firstClass);
  return 0;
}
1

No i co w związku z tym? Mamy ci pogratulować? Odpal program pod debugerem i zobacz gdzie popsułeś.
A błąd jest ewidentny: tworzysz FirstClass bez parametrów więc masz tam nulla jako wskaźnik do A1 a używasz operatora == który dereferuje ten wskaźnik. Brawo.

0

Gdzie jest błąd, to ja dobrze wiem. Pytanie: jak go naprawić?

0

Użyć mózgu? Nie dereferować nullowego wskaźnika? o_O Nie wiem jaką logikę porównywania obiektów chciałeś tu zastosować więc trudno odpowiedzieć jak dokładnie ten kod zmienić, bo można to zrobić na 100 sposobów.

0

Zmieniłem konstruktor na:

public:
    FirstClass()
      : a1(new A1()) {}

Teraz działa poprawnie.

0

No to zrobiłeś bez sensu. Teraz masz sytuacje taką że a1 zawsze się przydziela, więc nie ma sensu trzymać tego jako wskaźnik.

0

Więc jakie rozwiązanie proponujesz ?

0
class FirstClass
  {
    A1 a1;
   public:
   FirstClass() {}
   FirstClass(int x,int y):a1(x,y) {}
   bool operator==(const FirstClass& rhs)const { return (a1.x==rhs.a1.x)&&(a1.y==rhs.a1.y); }
  }; // destruktor i operator = nie są potrzebne

1 użytkowników online, w tym zalogowanych: 0, gości: 1