当在.cc源文件中设置为默认值时,移动构造函数和移动赋值操作符会抛出错误。

问题描述 投票:0回答:1

我有一个模板基类,大致是这样的

Vector.cc:

template<typename T, unsigned int D>
class Vector {

    private:
        T _data[D];

        ...

    public:
        Vector(Vector<T, D>&&);

        ...

    public:
        Vector<T, D>& operator=(Vector<T, D>&&);;
};

extern template class Vector<int, 2>;
extern template class Vector<int, 3>;
extern template class Vector<int, 4>;

Vector.h

// include guard

#include "Vector.h"

template<typename T, unsigned int D>
Vector<T, D>::Vector(Vector<T, D>&&) = default;

template<typename T, unsigned int D>
Vector<T, D>& Vector<T, D>::operator=(Vector<T, D>&&) = default;

template class Vector<int, 2>;
template class Vector<int, 3>;
template class Vector<int, 4>;

// include guard

当我编译这个文件时,我得到的错误是 error: array used as initializererror: invalid array assignment 和警告 note: synthesized method [...] first required here.

当我把 = default; 的声明中。.h 文件,我没有得到任何错误或警告。

我在多个资料中读到,我可以把文件中的 = default; 的定义中,但对我来说,它不工作。

我做错了什么?我错过了什么吗?还是我只是依赖了错误的资源?

c++ default move-constructor move-assignment-operator
1个回答
1
投票

问题是,默认的移动是无效的。在类内,编译器大概不会费心为它生成代码,因为它可能不会被使用。把它放在类外,可能会导致编译器决定编译 operatorconstructor。

用一个基本的例子来思考。

int array[5]; 
int array2[5]; 
array = array2;

上面的例子在C++中是无效的, 因为数组不能互相赋值.

在这种情况下,你必须为你的类创建自己的move operatorconstructor。

© www.soinside.com 2019 - 2024. All rights reserved.