【发布时间】:2017-10-26 23:57:33
【问题描述】:
当我运行下面的代码时,它会产生以下输出, 第一部分直接使用模板, 第二个使用从模板派生的类。 派生类中不调用移动语义(以粗体显示)
模板假人:初始化构造函数
模板假人:初始化构造函数
模板虚拟:空构造函数
模板虚拟:空构造函数
模板虚拟:+ 运算符
模板虚拟:移动赋值
2
模板假人:初始化构造函数
模板假人:初始化构造函数
模板虚拟:空构造函数
模板虚拟:空构造函数
模板虚拟:+ 运算符
模板虚拟:复制构造函数
模板虚拟:复制赋值
2
我认为原因很明确 - 命名参数会将参数转换为左值,因此模板接收左值并调用复制构造函数。
问题是在这种情况下如何强制移动语义?
#include <iostream>
using namespace std;
template <typename T> class Dummy {
public:
T val;
Dummy& operator=(const Dummy& d){
val = d.val;
cout << "Template Dummy: copy assignment\n" ;
return *this;
}
Dummy operator+(const Dummy &d) {
Dummy res;
res.val = val + d.val;
cout << "Template Dummy: + operator\n" ;
return res;
}
// constructors
Dummy() {
val = 0;
cout << "Template Dummy: empty constructor\n" ;
}
Dummy(const T v) {
val = v;
cout << "Template Dummy: initializing constructor\n" ;
}
Dummy(const Dummy &d) {
val = d.val;
cout << "Template Dummy: copy constructor\n" ;
}
// move semantics
Dummy(const Dummy&& d) {
val = d.val;
cout << "Template Dummy: move constructor\n" ;
}
Dummy& operator=(const Dummy&& d){
val = d.val;
cout << "Template Dummy: move assignment\n" ;
return *this;
}
};
class FloatDummy : public Dummy<float> {
public:
FloatDummy& operator=(const FloatDummy& d){
Dummy<float>::operator=(d);
return *this;
}
FloatDummy operator+(const FloatDummy &d) {
return (FloatDummy) Dummy<float>::operator+(d);
}
// constructors
FloatDummy() : Dummy<float>() {};
FloatDummy(float v) : Dummy<float>(v) {}
FloatDummy(const FloatDummy &d) : Dummy<float>(d) {}
FloatDummy(const Dummy<float> &d) : Dummy<float>(d) {}
// move semantics
FloatDummy(const FloatDummy&& d) : Dummy<float>(d) {}
FloatDummy& operator=(const FloatDummy&& d){
// here d is already an lvalue because it was named
// thus the template invokes a copy assignment
Dummy<float>::operator=(d);
return *this;
}
};
int main() {
Dummy<float> a(1), b(1);
Dummy<float> c;
c = a + b;
cout << c.val << '\n';;
FloatDummy d(1), e(1);
FloatDummy f;
f = d + e;
cout << f.val << '\n';
}
【问题讨论】:
-
从
const &&的所有情况中删除const,并使用std::move(d)从d移动
标签: c++ c++11 templates move-semantics