Reputation: 481
I have following problem: whats the best way to work on with a object which i got as parameter from my constructor? I don't want to work with the copy because, the initial object won't change.
Obj obj;
myclass::myclass(Obj& obj)
{
this->obj = obj; //copy
}
void myclass::doSometh()
{
obj.add(....); //working with the copy
}
My solution would be to use a 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 do you thing about my solution? or are there better solutions?
Upvotes: 1
Views: 90
Reputation: 15334
There is nothing wrong with using a pointer member-variable to avoid making a copy. But you do need to be confident that the object being pointed to, Obj
, will outlive the MyClass
which contains the pointer.
Also, I recommend using the constructor initializer list to initialize the pointer directly:
class MyClass {
private:
Obj* obj_;
public:
MyClass(Obj* obj) : obj_(obj) { }
};
In a similar way you could also have a reference member-variable but it restricts what you can do with the class. e.g it will not be assignable:
class MyClass {
private:
Obj& obj_;
public:
MyClass(Obj& obj) : obj_(obj) { }
};
If you are not confident of the lifetime of the object being pointed to 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) {
// do something with obj...
}
}
};
int main() {
std::shared_ptr<Obj> obj = std::make_shared<Obj>();
MyClass mc(obj);
}
Upvotes: 3
Reputation: 9648
Just use a reference:
Obj& obj;
myclass::myclass( Obj& obj ) : obj(obj) {}
Upvotes: 1