What is the function of “deleted” in the C programming language?

In the C language, “deleted” is a special identifier used to mark a member function or destructor as explicitly deleted. Functions marked as “deleted” cannot be called or accessed.

Some of the functions of deleted include:

  1. Preventing misuse: By marking a function as “deleted,” it can prevent the function from being mistakenly called or accessed, which can ultimately avoid potential runtime errors in certain situations.
  2. Explicitly disabling default functions: To disable the default copy constructor, move constructor, copy assignment operator, or move assignment operator, you can mark them as deleted. This will result in a compilation error when trying to call or access these functions.
  3. Provide better error messages: When a function is marked as deleted, the compiler will give relevant error messages when calling or accessing these functions. This helps developers to quickly identify and fix issues in the code.

Here are some examples of how it can be used:

class MyClass {
public:
    // 禁用默认的拷贝构造函数和拷贝赋值运算符
    MyClass(const MyClass&) = delete;
    MyClass& operator=(const MyClass&) = delete;

    // 禁用默认的移动构造函数和移动赋值运算符
    MyClass(MyClass&&) = delete;
    MyClass& operator=(MyClass&&) = delete;
};

int main() {
    MyClass obj1;
    MyClass obj2(obj1);  // 编译错误,拷贝构造函数被禁用

    MyClass obj3;
    obj1 = obj3;  // 编译错误,拷贝赋值运算符被禁用

    return 0;
}

In the example above, by marking the copy constructor and copy assignment operator as deleted, we have disabled the use of these default functions, preventing the copying of objects.

bannerAds