Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cassert>
- #include <iostream>
- #include <string>
- #include <vector>
- using namespace std;
- class Tentacle {
- public:
- explicit Tentacle(int id)
- : id_(id)
- {
- }
- int GetId() const {
- return id_;
- }
- private:
- int id_ = 0;
- };
- class Octopus {
- public:
- Octopus() {
- Tentacle* t = nullptr;
- try {
- for (int i = 1; i <= 8; ++i) {
- t = new Tentacle(i);
- tentacles_.push_back(t);
- t = nullptr;
- }
- } catch (const bad_alloc&) {
- Cleanup();
- delete t;
- throw;
- }
- }
- const Tentacle& GetTentacle(int index) const {
- if (index < 0 || static_cast<size_t>(index) >= tentacles_.size()) {
- throw out_of_range("Invalid tentacle index"s);
- }
- return *tentacles_[index];
- }
- ~Octopus() {
- Cleanup();
- }
- private:
- void Cleanup() {
- for (Tentacle* t : tentacles_) {
- delete t;
- }
- tentacles_.clear();
- }
- vector<Tentacle*> tentacles_;
- };
- int main(){
- {
- Octopus oc1;
- Octopus oc22 = oc1;
- cout << "Tentacle id = "s << oc22.GetTentacle(5).GetId() << endl;
- Octopus oc333 = oc1;
- cout << "Tentacle id = "s << oc333.GetTentacle(5).GetId() << endl;
- Octopus oc4444 = oc1;
- cout << "Tentacle id = "s << oc4444.GetTentacle(5).GetId() << endl;
- }
- cout << "OK"s << endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment