【发布时间】:2020-12-15 06:46:04
【问题描述】:
这段代码编译运行良好:
#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 的移动赋值运算符的代码复制了 Base 的代码。
有没有办法避免这种代码复制?
【问题讨论】:
-
使用
unique_ptr<int>,根本不写这些方法? -
您是否打算在
A类型的对象中拥有两个clean_副本? -
请注意:您知道
std::move不执行移动,而只是一个演员表?所以a_ = std::move(other.a_);没有多大意义,因为a_只是一个指针。 -
@t.niese 确保我明白了,你的意思是 a_=std::move(other.a_) 相当于 a_ = other.a_ ?
-
对于显示的代码,其结果是等效的。
std::move只是对r-value的强制转换,other.a_的值将在给定情况下的两种情况下被复制。所以在这种情况下你可以写a_ = other.a_。
标签: c++ inheritance move-semantics assignment-operator