diff options
| author | Friedemann Kleint <Friedemann.Kleint@qt.io> | 2022-03-17 14:16:33 +0100 |
|---|---|---|
| committer | Friedemann Kleint <Friedemann.Kleint@qt.io> | 2022-03-21 16:15:35 +0100 |
| commit | c3c692d26e2d6976afa226a3f49e1745e94712e7 (patch) | |
| tree | 2ecb64587c5a2250b9c3f6f95cff1f068c2e0970 /examples/samplebinding/truck.cpp | |
| parent | ec7ad296f48f3f1856c3eb7cc3685249a096d6b8 (diff) | |
Polish the samplebinding example
- Use a std::shared_ptr for internal storage.
- Simplify copy and assignment.
- Fix constness of the flavor accessor
- Add ostream operator to IceCream
Pick-to: 6.2
Change-Id: I814fa14095cbb96ab5642735e16b8b50101d4771
Reviewed-by: Cristian Maureira-Fredes <cristian.maureira-fredes@qt.io>
Diffstat (limited to 'examples/samplebinding/truck.cpp')
| -rw-r--r-- | examples/samplebinding/truck.cpp | 35 |
1 files changed, 14 insertions, 21 deletions
diff --git a/examples/samplebinding/truck.cpp b/examples/samplebinding/truck.cpp index c8b0d8988..d23991d9f 100644 --- a/examples/samplebinding/truck.cpp +++ b/examples/samplebinding/truck.cpp @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2018 The Qt Company Ltd. +** Copyright (C) 2022 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the Qt for Python examples of the Qt Toolkit. @@ -57,18 +57,14 @@ Truck::Truck(bool leaveOnDestruction) : m_leaveOnDestruction(leaveOnDestruction) Truck::Truck(const Truck &other) { - for (size_t i = 0; i < other.m_flavors.size(); ++i) { - addIcecreamFlavor(other.m_flavors[i]->clone()); - } + assign(other); } Truck &Truck::operator=(const Truck &other) { if (this != &other) { - clearFlavors(); - for (size_t i = 0; i < other.m_flavors.size(); ++i) { - addIcecreamFlavor(other.m_flavors[i]->clone()); - } + m_flavors.clear(); + assign(other); } return *this; } @@ -81,20 +77,18 @@ Truck::~Truck() { if (m_leaveOnDestruction) leave(); - clearFlavors(); } void Truck::addIcecreamFlavor(Icecream *icecream) { - m_flavors.push_back(icecream); + m_flavors.push_back(IcecreamPtr(icecream)); } void Truck::printAvailableFlavors() const { std::cout << "It sells the following flavors: \n"; - for (size_t i = 0; i < m_flavors.size(); ++ i) { - std::cout << " * " << m_flavors[i]->getFlavor() << '\n'; - } + for (const auto &flavor : m_flavors) + std::cout << " * " << *flavor << '\n'; std::cout << '\n'; } @@ -123,6 +117,13 @@ std::string Truck::getArrivalMessage() const return m_arrivalMessage; } +void Truck::assign(const Truck &other) +{ + m_flavors.reserve(other.m_flavors.size()); + for (const auto &f : other.m_flavors) + m_flavors.push_back(IcecreamPtr(f->clone())); +} + bool Truck::deliver() const { std::random_device rd; @@ -137,11 +138,3 @@ bool Truck::deliver() const return result; } - -void Truck::clearFlavors() -{ - for (size_t i = 0; i < m_flavors.size(); ++i) { - delete m_flavors[i]; - } - m_flavors.clear(); -} |
