I am not sure how to do this properly: I have class with a member variable which is pointer to MyOtherClass
class MyClass {
...
MyOtherClass* myOtherClassPtr;
...
}
And I have a factory function which returns instance of MyOtherClass by value. I want to copy that value so that the myOtherClassPtr points to it. Is the following code a proper way or there is a better way?
auto myOtherClassInstance = Factory::CreateInstance();
myOtherClassPtr = new MyOtherClass();
// this line should use copy assignment operator, is that correct?
*myOtherClassPtr = myOtherClassInstance;
Just fyi, MyOtherClass is implemented using pImpl and has all special members - header:
class MyOtherClass final {
public:
explicit MyOtherClass();
~ MyOtherClass();
// movable
MyOtherClass(MyOtherClass&& options) noexcept;
MyOtherClass& MyOtherClass =(MyOtherClass&& options) noexcept;
// copyable
MyOtherClass(const MyOtherClass&);
MyOtherClass& operator=(MyOtherClass& options);
...
private:
class Impl;
std::unique_ptr<Impl> impl_;
}
implementation:
class MyOtherClass::Impl {
...
}
MyOtherClass::MyOtherClass() : impl_(std::make_unique<Impl>()) {}
MyOtherClass::~MyOtherClass() = default;
MyOtherClass::MyOtherClass(MyOtherClass &&) noexcept = default;
MyOtherClass& MyOtherClass::operator=(MyOtherClass &&) noexcept = default;
MyOtherClass::MyOtherClass(const MyOtherClass& options)
: impl_(std::make_unique<Impl>(*options.impl_)) {}
MyOtherClass& MyOtherClass::operator=(MyOtherClass& options) {
swap(impl_, options.impl_);
return *this;
}
Also, MyClass is objective c class with myOtherClassPtr being atomic @property, but I thought it is not important for this question.
Aucun commentaire:
Enregistrer un commentaire