提问人:Louis 提问时间:6/24/2023 最后编辑:Louis 更新时间:6/25/2023 访问量:44
模板副本分配功能的混淆
Confusion on template copy assignment function
问:
[首先:Windows10 上的 Vs2019,仅支持 C++11]
我对模板复制分配功能感到困惑,例如:在此处输入图像描述
我发现规范化版本不起作用,为什么它不等于复制赋值功能?模板函数不是会像宏一样“扩展”吗?
让我们添加一个移动构造函数,如下所示:在此处输入图像描述
我知道用户声明的移动构造函数会将隐式复制赋值函数设置为删除。如果模板复制赋值函数不是“REAL”复制赋值函数,那么为什么编译器会说:
error C2280: 'TestClass &TestClass::operator =(const TestClass &)': attempting to reference a deleted function
message : compiler has generated 'TestClass::operator =' here
message : 'TestClass &TestClass::operator =(const TestClass &)': function was implicitly deleted because 'TestClass' has a user-defined move constructor
那么,编译器如何看待模板复制赋值函数呢? 需要明确的是: 如果template-assign-operator函数与copy-assign运算符不相同,为什么编译器会提醒我 'TestClass &TestClass::operator =(const TestClass &)':函数已隐式删除
提前致谢!
我希望模板复制分配函数的规范版本与复制分配函数相同。
完整的测试代码在这里:
class TestClass
{
public:
TestClass() {};
~TestClass() {};
// If the template function is not identical to copy assignment function
// why the compiler reports error:"function was implicitly deleted because 'TestClass' has a user-defined move constructor"
TestClass(TestClass&& rhs)
{
}
template <typename T>
TestClass& operator = (const T& rhs)
{
return *this;
}
// Why this is not identical to copy assignment function?
template<>
TestClass& operator = (const TestClass& rhs)
{
return *this;
}
};
int main()
{
TestClass A;
TestClass B;
B = A;
}
答: 暂无答案
评论