不实现和删除通用运算符有什么区别? [英] What is the difference between not implementing and deleting common operators?

查看:62
本文介绍了不实现和删除通用运算符有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我说一堂课

class Object
{
public:
    Object(int i) : num(i) {};

    int getNum() const { return num; }
private:
    int num;
};

现在,如果我尝试这样做

Now, if I try to do this

Object obj{ 1 };
Object obj2{ 2 };
Object obj3 = obj + obj2; //This is wrong

这是非法的:对象"未定义此运算符或未转换为预定义运算符可接受的类型.

This is illegal: 'Object' does not define this operator or a conversion to a type acceptable to the predefined operator.

添加 Object operator +(const Object&)= delete; 并不会真正改变任何东西,除了错误消息:'Object Object :: operator +(const Object&)':尝试引用已删除的函数.

Adding Object operator+(const Object&) = delete; doesn't really change anything, except for the error message: 'Object Object::operator +(const Object &)': attempting to reference a deleted function.

仅对具有隐式声明的运算符(例如赋值运算符和复制/移动构造函数)使用 delete 还是对我而言有其他更改?

Is the delete only needed for operators that have an implicit declaration (like assignment operator and copy/move constructor) or does it change anything else in my case?

推荐答案

删除仅适用于具有隐式声明的运算符(例如赋值运算符和复制/移动构造函数)还是对我而言是否会更改其他任何内容?

Is the delete only needed for operators that have an implicit declaration (like assignment operator and copy/move constructor) or does it change anything else in my case?

不,不.您的案子太简单了,根本无所谓.

No and no. Your case is merely too simple for any such difference to matter.

=删除有两个用途:

1:它会强制删除原本可能存在的功能.即,特殊的成员函数.

1: It forcibly removes functions which would (potentially) otherwise be there. Namely, the special member functions.

2:它指定具有该签名的函数不能被调用.这本质上是#1的概括.

2: It specifies that a function with that signature cannot be called. This is essentially a generalization of #1.

后者的原型示例用于防止函数参数的隐式转换.如果您这样做:

The archetypal example of the latter is for preventing implicit conversion of function arguments. If you do this:

void foo(float val);
void foo(int) = delete;

您不能再调用 foo(5);您必须使用 foo(5.f).为什么?由于编译器将看到第二次重载,因此请确保它与最佳调用相匹配,然后由于删除了该函数而立即失败.

You can no longer call foo(5); you must use foo(5.f). Why? Because the compiler will see the second overload, see that it matches the call the best, and then immediately fail because the function is deleted.

有时也可以这样做:

void foo(float val);
template<typename T> void foo(T&&) = delete;

这可确保您只能使用实际的 float 进行 调用.无法从 float 隐式转换的类型将起作用.

This ensures that you can only call it with an actual float. No type which is implicitly convertible from float will work.

这篇关于不实现和删除通用运算符有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆