c++ 这个移动和复制 Package 是否健全和完整?

2eafrhcq  于 2023-06-25  发布在  其他
关注(0)|答案(1)|浏览(140)

我只是为移动和复制操作做了一个 Package 器,以注入到代码中,看看在默认实现的情况下调用了哪个。我越来越接近理解什么是所谓的,但想再次检查的时候。
我不确定using T::T;的方法1对于构造函数来说是否比方法2更好,方法2转发了unique_ptr之类的参数。我在这个帖子里找到了Forwarding all constructors in C++0x
在移动构造函数和赋值中,我使用std::move传递给超类。这应该是std::forward吗?如果是,怎么做?我尝试使用它时出错。

  1. #ifndef MOVECOPY_OBSERVER_H
  2. #define MOVECOPY_OBSERVER_H
  3. #include <iostream>
  4. template<class T>
  5. class MoveCopyObserver : public T {
  6. public:
  7. //1: Use "using" for constructors
  8. //From https://stackoverflow.com/questions/3119929/forwarding-all-constructors-in-c0x
  9. using T::T;
  10. //2: Forward all args, unique_ptr style.
  11. /*
  12. template<typename... Args>
  13. MoveCopyObserver(Args&&... args)
  14. : T(std::forward<Args>(args)...)
  15. {
  16. };*/
  17. // *************************************************************************
  18. virtual ~MoveCopyObserver() = default;
  19. // *************************************************************************
  20. MoveCopyObserver(const MoveCopyObserver& other)
  21. : T(other)
  22. {
  23. std::cout << "Copy constructor " << typeid(T).name() << std::endl;
  24. }
  25. // *************************************************************************
  26. MoveCopyObserver(MoveCopyObserver && other)
  27. : T(std::move(other)) //3: std::forward instead?
  28. {
  29. std::cout << "Move constructor " << typeid(T).name() << std::endl;
  30. }
  31. // *************************************************************************
  32. MoveCopyObserver& operator=(const MoveCopyObserver& other)
  33. {
  34. T::operator=(other);
  35. std::cout << "Copy assignment " << typeid(T).name() << std::endl;
  36. return *this;
  37. }
  38. // *************************************************************************
  39. MoveCopyObserver& operator=(MoveCopyObserver&& other)
  40. {
  41. T::operator=(std::move(other)); //3: std::forward instead?
  42. std::cout << "Move assignment " << typeid(T).name() << std::endl;
  43. return *this;
  44. }
  45. };
  46. #endif //MOVECOPY_OBSERVER_H

使用方法是在堆栈上或通过智能指针,如下所示:

  1. class A {
  2. public:
  3. A(std::string ss)
  4. {
  5. s = ss;
  6. }
  7. void f()
  8. {
  9. std::cout << "\"" << s << "\"" << std::endl;
  10. }
  11. private:
  12. std::string s;
  13. };
  14. A a("Test instance");
  15. a.foo();
  16. MoveCopyObserver<A> b("Another instance");
  17. b.foo();
aydmsdu9

aydmsdu91#

另一个问题解决了继承构造函数的问题,它确实在几个方面上级转发 Package 器。请注意,neither方法为您提供了复制/移动构造函数(出于不同的原因),这在这里很好,因为您希望记录这些。
std::forward用于转发引用;你不需要或不需要这些(甚至T&&class模板中的普通右值引用),所以std::move在这里是正确的。

相关问题