TGViewer
Art of Code Art of Code @codeof_art · 2.18K subscribers
Post #251 11.5K
Задача с собеса в Ягуар

Задача: Напишите конструктор копирования для A. Для тех кто неуверенно (с подсказкой) справился с предыдущей задачей: напишите operator= для класса A. чтобы проверить, что всё поняли.

class Cloneable {
public:
virtual Cloneable* clone() const = 0; // Возвращает копию себя
virtual ~Cloneable() {}
};

class A {
public:
A(/* Какой должна быть сигнатура конструктора копирования? */);
~A();

// Добавить оператор присваивания

private:
Cloneable* b;
Cloneable* c;
std::string* s;
};

A::~A() {
delete b;
delete c;
delete s;
}


Решение:

Конструктор копирования: A::A(const A& other)
: b(other.b ? other.b->clone() : nullptr),
c(other.c ? other.c->clone() : nullptr),
s(other.s ? new std::string(*other.s) : nullptr) {}

Оператор присваивания: A& A::operator=(const A& other) {
if (this != &other) { // Проверка на самоприсваивание
// Удаляем старые данные
delete b;
delete c;
delete s;

// Копируем новые данные
b = other.b ? other.b->clone() : nullptr;
c = other.c ? other.c->clone() : nullptr;
s = other.s ? new std::string(*other.s) : nullptr;
}
return *this;
}


Полный код: class A {
public:
A() : b(nullptr), c(nullptr), s(nullptr) {} // Конструктор по умолчанию
A(const A& other); // Конструктор копирования
A& operator=(const A& other); // Оператор присваивания
~A();

private:
Cloneable* b;
Cloneable* c;
std::string* s;
};

// Реализации
A::A(const A& other)
: b(other.b ? other.b->clone() : nullptr),
c(other.c ? other.c->clone() : nullptr),
s(other.s ? new std::string(*other.s) : nullptr) {}

A& A::operator=(const A& other) {
if (this != &other) {
delete b;
delete c;
delete s;
b = other.b ? other.b->clone() : nullptr;
c = other.c ? other.c->clone() : nullptr;
s = other.s ? new std::string(*other.s) : nullptr;
}
return *this;
}

A::~A() {
delete b;
delete c;
delete s;
}


@codeof_art
  • 🔥 3
  • ❤ 2
  • ❤‍🔥 2
More from @codeof_art
  1. Sep 22, 2026Новый пост из серии про паттерны на реальном коде. Разбираем штуку, с которой рано или поз…
  2. Sep 21, 2026Полный цикл собесов в Яндекс (Бэкенд 2026) Сейчас студенты наших курсов под чутким сопрово…
  3. Sep 20, 2026❗️ Яндекс открыл Intern Week Offer на стажировку, где всего за неделю ты можешь получить о…
  4. Sep 19, 2026Товарищи, Поступашкам нужны контент мейкеры в основной канал по алгоритмам и другим дисцип…
  5. Sep 17, 2026System Design: backend Сегодня разберём задачу, которую мне давали на собесе в Яндекс. Шту…
  6. Sep 16, 2026В Яндекс без опыта с первого раза Товарищи, продолжаем рассказывать про наших талантливых…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →