Approach 1
I have some type Foo which internally contains a std::mutex.
class Foo {
std::mutex m_;
};
I wrote another class Bar. Bar has Foo as a member and a constructor, like this (note - this code doesn't compile):
class Bar {
Bar(Foo foo) : foo(foo) {}
...
private:
Foo foo;
};
My IDE complains:
Call to implicitly-deleted copy constructor of Foo. copy constructor of 'Foo' is implicitly deleted because field 'm_' has a deleted copy constructor
Approach 2
So then I tried to do an assignment like this:
class Bar {
Bar(Foo fooIn) { foo = fooIn; }
...
private:
Foo foo;
};
But this also says:
Object of type 'Foo' cannot be assigned because its copy assignment operator is implicitly deleted
Approach 3 (using pointer)
The only way I can get this to work is like this:
class Foo {
private:
std::mutex m_;
};
class Bar {
Bar(std::unique_ptr<Foo> fooIn) : foo(std::move(fooIn)) {}
private:
std::unique_ptr<Foo> foo;
};
I understand the smart pointer helps with memory management. But lets put that feature aside.
In my examples above, the main difference between not using the smart pointer and using the smart pointer is that the smart pointer has indirection – it's pointing to an object on the heap. Right?
What is the right mental model to understand this? Is it that because Foo has a deleted copy constructor and deleted copy assignment, my only option is to have it constructed on the heap and then work via indirection (via pointers)?
Is that correct? Or am I completely off?
Aucun commentaire:
Enregistrer un commentaire