Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this enum for in the destructor?

Tags:

c++

// Destructor.  If there is a C object, delete it.
// We don't need to test ptr_ == NULL because C++ does that for us  

    ~scoped_ptr() {
       enum { type_must_be_complete = sizeof(C) };
       delete ptr_;
    }

Note: C is a template parameter

I know we cant delete a null pointer, an exception will be raised. So in this case, the enum definition must be doing something to prevent that. In production, sometimes we dont want to end a program simple because we have a null pointer, we may want to look at alternative scenario, when the pointer is null. And this code is used in production, almost everywhere?

Thanks guys.

like image 889
maress Avatar asked Apr 23 '12 07:04

maress


People also ask

What is an enum in C++?

Enum, which is also known as enumeration, is a user-defined data type that enables you to create a new data type that has a fixed range of possible values, and the variable can select one value from the set of values.

Can we use this pointer in destructor?

In one word: YES.

Can we pass parameters to Destructor C#?

So no, destructors do not take parameters.

Can we delete this pointer in destructor?

Answer: Yes, we can delete “this” pointer inside a member function only if the function call is made by the class object that has been created dynamically i.e. using “new” keyword.


1 Answers

it's effectively a static assertion for the deletion. the implementation wants to know if it is dealing with a type whose declaration is visible before deleting the variable, rather than a forward declaration.

Your compiler will emit an error when you ask it the size of an incomplete type:

struct S;
enum { Size = sizeof(S) };

Update

As your compiler and Matthieu M. will tell you -- delete-ing an incomplete type is undefined.

like image 125
justin Avatar answered Nov 14 '22 16:11

justin