在每个 class 中显式声明默认的移动构造函数是否不提供用户定义的一个好习惯?
Is declaring explicitly defaulted move constructor in every class that doesn't provide user-defined one a good practice?
有相当复杂的(对我来说)rules 定义隐式默认移动构造函数何时生成以及何时不生成。我担心的是不会生成默认的移动构造函数。另外我担心我(或其他人)将来修改 class 并且隐式移动构造函数将消失。
有一个"advice"表示"you can always explicitly invoke the default generation for functions that can be automatically generated with = default
(that's what the syntax is for)"。现在我问:这是个好主意吗?有什么理由不这样做吗?我想如果没有问题那么我们就不需要默认的移动构造函数,移动构造函数总是会被生成。但由于标准定义了如此严格的规则,因此可能有这样做的理由。
考虑以下场景。你有一个 class 可以与 auto-generated 移动构造函数和析构函数:
class X {
int i_;
public:
X(int i) : i_(i) { }
};
那么,以后你添加一个成员变量,需要user-defined拷贝构造函数和析构函数:
class X {
int i_;
char* buf_;
size_t n_;
public:
X(int i, size_t n) : i_(i), n_(n), buf_(new char[n]) { }
X(const X& o) : i_(o.i_), n_(o.n_), buf_(new char[o.n_]) { memcpy(buf_, o.buf_, n); }
~X() { delete[] buf_; }
};
如果在此处 default
编辑移动构造函数,新的 class 版本将是错误的。
没有 default
ed 移动构造函数,根据 rules-of-five 修改 class 就可以了,如果 5 个特殊的之一function 必须是 user-defined,其他函数也可能需要 user-defined。如果需要,您现在必须手动定义移动构造函数。
有相当复杂的(对我来说)rules 定义隐式默认移动构造函数何时生成以及何时不生成。我担心的是不会生成默认的移动构造函数。另外我担心我(或其他人)将来修改 class 并且隐式移动构造函数将消失。
有一个"advice"表示"you can always explicitly invoke the default generation for functions that can be automatically generated with = default
(that's what the syntax is for)"。现在我问:这是个好主意吗?有什么理由不这样做吗?我想如果没有问题那么我们就不需要默认的移动构造函数,移动构造函数总是会被生成。但由于标准定义了如此严格的规则,因此可能有这样做的理由。
考虑以下场景。你有一个 class 可以与 auto-generated 移动构造函数和析构函数:
class X {
int i_;
public:
X(int i) : i_(i) { }
};
那么,以后你添加一个成员变量,需要user-defined拷贝构造函数和析构函数:
class X {
int i_;
char* buf_;
size_t n_;
public:
X(int i, size_t n) : i_(i), n_(n), buf_(new char[n]) { }
X(const X& o) : i_(o.i_), n_(o.n_), buf_(new char[o.n_]) { memcpy(buf_, o.buf_, n); }
~X() { delete[] buf_; }
};
如果在此处 default
编辑移动构造函数,新的 class 版本将是错误的。
没有 default
ed 移动构造函数,根据 rules-of-five 修改 class 就可以了,如果 5 个特殊的之一function 必须是 user-defined,其他函数也可能需要 user-defined。如果需要,您现在必须手动定义移动构造函数。