Destructors of builtin types (int, char etc..)

前端 未结 1 988
长发绾君心
长发绾君心 2020-11-27 03:53

In C++ the following code gives a compiler error:

void destruct1 (int * item)
{
  item->~int();
}

This code is nearly the same, I just t

相关标签:
1条回答
  • 2020-11-27 03:57

    It's the reason that makes your code work for generic parameters. Consider a container C:

    template<typename T>
    struct C {
        // ...
        ~C() {
            for(size_t i = 0; i<elements; i++)
                buffer[i].~T();
        }
    };
    

    It would be annoying to introduce special cases for built-in types. So C++ allows you to do the above, even if T happens to equal to int. The holy Standard says in 12.4 p15:

    The notation for explicit call of a destructor can be used for any scalar type name. Allowing this makes it possible to write code without having to know if a destructor exists for a given type.

    The difference between using a plain int and a typedef'ed int is that they are syntactically different things. The rule is, that in a destructor call, the thing after the ~ is a type-name. int is not such a thing, but a typedef-name is. Look it up in 7.1.5.2.

    0 讨论(0)
提交回复
热议问题