c++ - working with parameter from the constructor -
i have following problem: whats best way work on object got parameter constructor? don't want work copy because, initial object won't change.
obj obj; myclass::myclass(obj& obj) { this->obj = obj; //copy } void myclass::dosometh() { obj.add(....); //working copy }
my solution use pointer:
obj* obj; void myclass::myclass(obj& obj) { this->obj = &obj; } void myclass::dosometh() { obj->add(....); }
or
obj* obj; myclass::myclass(obj* obj) { this->obj = obj; } void myclass::dosometh() { obj->add(....); }
what thing solution? or there better solutions?
there nothing wrong using pointer member-variable avoid making copy. need confident object being pointed to, obj
, outlive myclass
contains pointer.
also, recommend using constructor initializer list initialize pointer directly:
class myclass { private: obj* obj_; public: myclass(obj* obj) : obj_(obj) { } };
in similar way have reference member-variable restricts can class. e.g not assignable:
class myclass { private: obj& obj_; public: myclass(obj& obj) : obj_(obj) { } };
if not confident of lifetime of object being pointed consider std::weak_ptr
or std::shared_ptr
:
#include <memory> struct obj { }; class myclass { private: std::weak_ptr<obj> obj_; public: myclass(std::weak_ptr<obj> obj) : obj_(std::move(obj)) { } void dosomething() { std::shared_ptr<obj> obj = obj_.lock(); if (obj) { // obj... } } }; int main() { std::shared_ptr<obj> obj = std::make_shared<obj>(); myclass mc(obj); }
Comments
Post a Comment