【发布时间】:2015-03-12 00:57:16
【问题描述】:
有没有更好的方法来为类联合类构建移动构造函数?如果我有一个类似联合的类,比如下面代码中的类,有没有办法构建类或移动构造函数,不需要像下面代码中的移动构造函数那样的 switch 语句。
class S {
private:
enum {CHAR, INT, DOUBLE} type; // tag
// anonymous union
union {
char c;
int n;
double d;
};
public:
// constructor if the union were to hold a character
AS(const char c) {
this->tag = AS::CHAR;
this->c = c;
}
// constructor if the union were to hold a int
AS(const int i) {
this->tag = AS::INT;
this->n = i;
}
// constructor if the union were to hold a double
AS(const double d) {
this->tag = AS::DOUBLE;
this->d = d;
}
// Move constructor with switch statement
S(S &&src) : type(std::move(src.type)) {
switch(type) {
case CHAR:
this->c = src.c);
src.c = 0;
break;
case INT:
this->n = src.n;
src.n = 0;
break;
case DOUBLE:
this->d = src.d;
src.d = 0
break;
default:
break;
}
}
};
【问题讨论】:
-
取决于您的编译器。 gcc 支持通过联合进行类型双关,因此无论如何您都可以简单地分配最大的元素
-
如果您的真实类只包含基本数据类型或 POD 结构,我根本不会费心定义自定义移动构造函数,因为无论如何它只是一个副本。之后不必将源数据类型设置为 0,因为无论如何您都不应该再次读取它。
-
例外:如果其中一个结构巨大而其他成员很小,则选择性复制/移动可能会有好处。
-
@NeilKirk 在这个类所拥有的
union中不可能有一个指针类型吗?如果是这样,那么移动语义将避免对深拷贝的需要? -
@JamesAdkison 是的。我假设没有指针欺骗。不过我没有说清楚。
标签: c++ c++11 unions move-constructor