c ++:移动分配运算符和继承 [英] c++ : move assignement operator and inheritance

查看:132
本文介绍了c ++:移动分配运算符和继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码可以编译并正常运行:

This code compiles and runs fine:

#include <iostream>

class Base
{
  public:
  Base(int value)
  : clean_(true)
  {
      value_ = new int;
      *value_ = value;
  }
  ~Base()
  {
      if(clean_)
        delete value_;
  }
  Base(Base&& other) noexcept 
  : value_{std::move(other.value_)},
    clean_(true)
  {
      other.clean_=false;
  }
  Base& operator=(Base&& other) noexcept
  {
      value_ = std::move(other.value_);
      other.clean_=false;
      clean_=true;
  }
  void print()
  {
      std::cout << value_ << " : " << *value_ << std::endl;
  }
  
  int* value_;
  bool clean_;
    
};

class A : public Base 
{
  public:
  A(int v1, double v2) : Base(v1)
  {
      a_ = new double;
      *a_ = v2;
  }
  A(A&& other) noexcept
  : Base(std::forward<Base>(other)),
    a_(std::move(other.a_))
  {}
  A& operator=(A&& other) noexcept
  {
      // should not the move assignment operator
      // of Base be called instead ? 
      // If so: how ?
      this->value_ = std::move(other.value_);
      other.clean_=false;
      this->clean_=true;
      a_ = std::move(other.a_);
  }
  void print()
  {
      std::cout << this->value_ << " "
                << *(this->value_) << " "
                << a_ << " " << *a_ << std::endl;
  }

  double* a_;
  bool clean_;
    
};

A create_a(int v1,double v2)
{
    A a(v1,v2);
    return a;
}

int main()
{
    Base b1(20);
    b1.print();
    
    Base b2 = std::move(b1);
    b2.print();
    
    A a1(10,50.2);
    a1.print();
    
    A a2 = std::move(a1);
    a2.print();
    
    A a3 = create_a(1,2);
    a3.print();
}

A是Base的子类.

A is a subclass of Base.

A的移动分配运算符的代码复制了Base中的一个.

The code of the move assignment operator of A replicates the one of Base.

有没有办法避免这种代码重复?

Is there a way to avoid this replication of code ?

推荐答案

int * value _; 更改为 int value _; double * a _; double a _; ,并且您不再需要编写任何特殊的成员函数,因为编译器提供了默认的Just Work™

Change int* value_; to int value_; and double* a_; to double a_; and you no longer need to write any of the special member functions as the compiler provided defaults Just Work™

如果您确实需要动态内存分配,请使用 RAII类型例如 std :: vector std :: unique_ptr std :: shared_ptr 等.因为它们是为了正确复制和移动而设计的.

If you really need dynamic memory allocation, then use a RAII type like std::vector, std::unique_ptr, std::shared_ptr, ect. in its place since they are designed to be copied and or moved correctly.

这篇关于c ++:移动分配运算符和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆