问题描述
我有2个课程:
template<typename T>
class base{
T t;
public:
base(base &&b): t(std::move(b.t)){}
};
template<typename T, typename T2>
class derived : protected base<T>{
T2 t2;
public:
derived(derived &&d): base<T>(std::move(d)), t2(std::move(d.t2)){}
};
我将整个d
对象移到derived
move-constructor
中以初始化base
部分,并且d
变为无效,但是我仍然需要它来将其用于t2
初始化
I move entire d
object in the derived
move-constructor
to initialize base
part and d
becomes invalid but I still need it to use it's part for t2
initialization
有可能做这样的事情吗?
Is it possible to do such a thing?
推荐答案
我会说您的构造是正确的,除了一些语法错误,您需要在初始化列表中限定base<T>
:
I would say that your construct is correct except for a little syntax error, you need to qualify base<T>
in the initializer list:
derived(derived &&d): base<T>(std::move(d)), t2(std::move(d.t2)){}
首先,初始化的顺序与初始化列表的顺序无关. n4296草案在 12.6.2中声明初始化基础和成员[class.base.init]§13
First, the order of initialization is independant of the order of the initializer list. Draft n4296 says in 12.6.2 Initializing bases and members [class.base.init] § 13
[注意:声明顺序是强制性的,以确保在子对象中销毁基础和成员子对象. 初始化的相反顺序. —尾注]
[ Note: The declaration order is mandated to ensure that base and member subobjects are destroyed in the reverse order of initialization. —end note ]
我们也有§7或同一章说:
We have also §7 or same chapter that says:
我的理解是,标准表示在derived
类的移动ctor中,事情按以下顺序发生:
My understanding is that standard says that in the move ctor for the derived
class, things happens in that order:
- 为基类移动ctor称为
- 依次调用T的move ctor有效地构造目标的t成员,并最终将源的t成员清零
- move ctor for base class is called
- in turn it calls move ctor for T effectively constructing t member of target and eventually zeroing t member of source
这篇关于移动派生类的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!