【发布时间】:2022-07-06 12:31:59
【问题描述】:
我遇到了这种奇怪的情况:
template <typename pointed_t>
class MyPointer
{public:
MyPointer() : pPointed(nullptr) {}
/* PREVENT COMPILER-GENERATED FUNCTIONS */
MyPointer(const MyPointer&);
MyPointer(MyPointer&&);
MyPointer& operator=(const MyPointer&);
MyPointer& operator=(MyPointer&&);
//----------
pointed_t* pPointed;
/* COPY CONSTRUCTOR */
template <typename AnyPointerType>
MyPointer(AnyPointerType& other)
{
}
/* MOVE CONSTRUCTOR */
template <typename AnyPointerType>
MyPointer(AnyPointerType&& other)
{
}
};
int main()
{
MyPointer<char> p1;
MyPointer<char> p2 = p1; // COPY CONSTRUCTOR CALLED FINE
MyPointer<char> p3 = std::move(p1); // RAISES BELOW LINKER ERROR
/* Unresolved external symbol
public: __cdecl MyPointer<char>::MyPointer<char>(class MyPointer<char> &&)" */
}
所以 p2 = p1;调用模板复制构造函数很好,但 p3 = std::move(p1);不能调用模板化的移动构造函数?
所以结果是复制构造函数工作,但移动构造函数没有。除非它是不同的类型:
MyPointer<float> p1;
MyPointer<char> p2 = std::move(p1); // NOW THE TEMPLATED MOVE CONSTRUCTOR IS CALLED FINE
有人可以帮我理解为什么没有调用模板化移动构造函数吗?
【问题讨论】:
-
MyPointer(MyPointer&&);定义在哪里? -
模板永远不是复制/移动构造函数。可能是骗人的:stackoverflow.com/questions/55845896/…
-
@Eljay 不是故意定义的,我不希望编译器调用它。我不希望它自动生成,我不希望它被调用,我希望我的模板被调用。
-
通过声明移动构造函数,它参与了重载解析。由于它没有定义,它会导致链接器错误。 (鉴于 NathanOliver 的评论,您想要采取的方法可能是不可能的。)
-
@Eljay 但是为什么复制构造函数不会失败?这也没有定义。
标签: c++ templates move-semantics