struct child{ child(parent& object) noexcept : m_parent(&object) {} parent& getParent() noexcept { return *this->m_parent; } void setParent(parent& object) noexcept { this->m_parent = &parent; } void work() { // указатель this->m_parent априори валидный }private: parent* m_parent;};
class Foo{public: using BarPtr = std::unique_ptr<Bar>; void setBar(BarPtr bar) { m_bar = std::move(bar); } void doBaz() { m_bar->baz(); } BarPtr m_bar;};
class Foo{ using BarPtr = std::shared_ptr<Bar>; // поменялось раз void setBar(BarPtr bar) { m_bar = std::move(bar); } void doBaz() { m_bar->baz(); } BarPtr m_bar;};
class Foo{public: void setBar(Bar &&bar) { m_bar = std::move(bar); } void doBaz() { m_bar.baz(); }private: Bar m_bar;};
class Foo{ using BarPtr = std::shared_ptr<Bar>; // добавилось void setBar(BarPtr bar) { m_bar = std::move(bar); } // поменялось раз void doBaz() { m_bar->baz(); } // поменялось два (точка на ->) BarPtr m_bar; // поменялось три};
C++ (Qt)#include <iostream> struct parent{ std::string name;}; struct child{ child(const parent& mother, const parent& father) noexcept : m_mother{&mother}, m_father{&father} {} const parent& getMother() noexcept { return *this->m_mother; } const parent& getFather() noexcept { return *this->m_father; } void setParents(const parent& mother, const parent& father) noexcept { this->m_mother = &mother; this->m_father = &father; } void work() { std::cout << "mother: " << getMother().name << std::endl; std::cout << "father: " << getFather().name << std::endl; } private: const parent* m_mother; const parent* m_father;}; int main(){ parent mother{"Marfa"}; parent father{"Miron"}; child son{mother, father}; son.work(); son.setParents(parent{"Stepanida"}, parent{"Stepan"}); son.work(); return 0;}
son.setParents(&parent{"Stepanida"}, &parent{"Stepan"});
auto* object = api::create();assert(object);work(*object); // <--- это так сложно?