【发布时间】:2014-10-04 11:25:30
【问题描述】:
我熟悉的原理(例如,来自this answer 和this one)当一个类有一个移动构造函数和/或移动赋值运算符时,它的默认复制构造函数和复制赋值运算符被删除。但是,在我看到的示例中,这可以通过显式定义新的复制构造函数和赋值运算符来解决。
在我的特定情况下,我有一个类,它是通过从 C 样式结构和模板类的联合继承派生的。复制和移动赋值运算符在模板中显式定义,而复制和移动构造函数在类本身中显式定义。换句话说,一切都是明确定义的,虽然不是都在同一个地方。下面是一些示例代码:
typedef struct {
int n;
} myStruct;
template <typename T> class myTemplate
{
public:
// Default constructor
myTemplate<T>() : t_n(nullptr) {}
// Cannot create copy or move constructors in template, as cannot
// access the 'n' member directly
// Copy assignment operator
myTemplate<T> & operator=(const myTemplate<T> &source)
{
if (this != &source)
{
*t_n = *(source.t_n);
}
return *this;
}
//! Move assignment operator
myTemplate<T> & operator=(myTemplate<T> &&source)
{
if (this != &source)
{
*t_n = *(source.t_n);
*(source.t_n) = 0;
source.t_n = nullptr;
}
return *this;
}
T* t_n;
};
class myClass : public myStruct, public myTemplate<int>
{
public:
// Default constructor
myClass() : myTemplate<int>()
{
n = 0;
t_n = &n;
}
// Alternative constructor
myClass(const int &n_init) : myTemplate<int>()
{
n = n_init;
t_n = &n;
}
// Copy constructor
myClass(const myClass &source) : myTemplate<int>()
{
n = source.n;
t_n = &n;
}
// Move constructor
myClass(myClass &&source) : myTemplate<int>()
{
n = source.n;
t_n = &n;
source.n = 0;
source.t_n = nullptr;
}
};
int main()
{
myClass myObject(5);
myClass myOtherObject;
// Compilation error here:
myOtherObject = myObject;
return 1;
}
在 Windows 上的 Visual C++ 和 Intel C++ 中,这完全符合我的预期。然而,在 Linux 中的 gcc 4.9.0 上,我收到了可怕的错误消息:
g++ -c -std=c++11 Main.cppMain.cpp: In function ‘int main()’:
Main.cpp:78:19: error: use of deleted function ‘myClass& myClass::operator=(const myClass&)’
myOtherObject = myObject;
^
Main.cpp:39:7: note: ‘myClass& myClass::operator=(const myClass&)’ is implicitly declared as deleted because ‘myClass’ declares a move constructor or move assignment operator
class myClass : public myStruct, public myTemplate<int>
果然,如果我在类本身而不是在模板中定义显式复制赋值运算符,错误就会消失,但这很麻烦,并且破坏了使用模板的优势,因为 (a) 我的实际副本赋值运算符比这里显示的要大得多,并且 (b) 有大量不同的类都共享这个模板。
那么,这仅仅是 gcc 4.9.0 中的一个错误,还是实际上标准所说的应该发生?
【问题讨论】:
-
只需明确默认
myClass中的赋值运算符即可。这不是负担。
标签: c++ c++11 multiple-inheritance move-semantics