超载分配运算符和零规则
我已经写了一个模板类a< t>
,并且正在使用零规则(我让编译器生成destructor,复制/移动构造函数和分配运算符过载)。 但是,我现在需要一个自定义的分配运算符,该操作员以不同的类型b< t>
作为参数:
A<T>& operator=(const B<T>& rhs);
此实现会阻止编译器生成默认的驱动器等吗? 我的猜测是不,因为编译器生成的生成
A<T>& operator=(const A<T>& rhs);
与我要实施的过载完全不同。
I have written a template class A<T>
and I am making use of the rule of zero (I let the compiler generate the destructor, copy/move constructors and assignment operator overloadings).
However, I need now a customized assignment operator that takes a different type B<T>
as argument:
A<T>& operator=(const B<T>& rhs);
Will this implementation prevent the compiler from generating the default destructor etc.?
My guess is no, because the compiler generates
A<T>& operator=(const A<T>& rhs);
which is just entirely different from the overloading I want to implement.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据我的理解,添加
oterator =
Overload将不是防止编译器根据0的规则生成默认的编译器。我以此为基础
操作员=
Overload是不是实际上a 复制分配 , nor a 移动分配 。因此,有关通用默认构造函数和分配运算符的规则无关。。
我用MSVC进行了验证。
您可以使用下面的代码来验证编译器:
输出应为: 6,5,3 :
6 是值
a&lt; int&gt; A2
由 5 构建是从a&lt; int&gt; A1
和 3 是从b&lt; int&gt; B
。注意:替代方案是使用用户定义的转换函数,如@louisgo所述(请参见上文)。
According to my understanding, adding a
operator=
overload will not prevent the compiler from generating the default one according to the rule of 0.I base this understanding on the fact that your
operator=
overload is not in fact a copy assignment, nor a move assignment.Therefore the rules about generaing default constructors and assignment operators are not relevant.
I verified it with MSVC.
You can use the code below to verify with your compiler:
The output should be: 6,5,3:
6 is the value
A<int> a2
is constructed with, 5 is the value assigned fromA<int> a1
, and 3 is the value assigned fromB<int> b
.Note: an alternative would be to use a user-defined conversion function, as @LouisGo commented (see above).