Move constructor and = operator for generic pointer

Let's say I have a class:

class GameObject ///header file
{
    ....
    std::shared_ptr<Transform> transform;
}
///cpp file
//Copy Ctor
GameObject::GameObject(const GameObject& rhs)
   :transform(rhs.transform)
{}
//Move CTor
GameObject::GameObject(GameObject&& rhs)
    :transform(std::move(rhs.transform))
{}
  • Is it right to create a move constructor for a class with member_ptr? Or do I need to call rhs.transform.reset()to cancel the allocation of rhs after the move?
  • What about copy constructor?
  • Presumably, copy and move destinations look basically the same as ctors, only with return *thisat the end?
+4
source share
3 answers

. . , std::shared_ptr .

rhs.transform.reset() rhs ?

, :

shared_ptr(shared_ptr&& r) noexcept;
template<class Y> shared_ptr(shared_ptr<Y>&& r) noexcept;

. , Y* T*.

: Move-constructs shared_ptr r. : *this r. r . r.get() == nullptr.

, . - , - , shared_ptr .

( ), shared_ptr . unique_ptr, .

+9
  • . GameObject , transform. shared_ptr - transform. reset(), - -, , shared_ptr , , .

  • , shared_ptr .

  • .

: , , . / -, . 5 , :

class GameObject {
    std::shared_ptr<Transform> transform;
    std::shared_ptr<SomethingElse> foo;
};

GameObject obj = ...;
GameObject obj2 = obj;             // correct by default
GameObject obj3 = std::move(obj2); // correct by default
+1
  • shared_ptr shared_ptr , reset().

  • Transform GameObject s. , , . , - transform(new Transform(*rhs.transform)).

  • , ( ). . , copy-and-swap, :

    GameObject &operator=(const GameObject &rhs) {
      GameObject tmp(rhs);
      tmp.swap(*this);
      return *this;
    }
    

, , ( ), .

0

All Articles