Why can't a destructor have reference qualifiers?

218 views Asked by At

Is there a reason (other than because the standard says so) to why the following code is not allowed?

struct Foo
{
    ~Foo() && {}
    ~Foo() & {}
};

I know that it is illegal, but I wanna know why.

I was thinking about the good old avoid unnamed instances problem, i.e. when using guard objects, like:

void do_something()
{
    std::lock_guard{my_mutex};
    // some synchronized operation
}

This is legal code but obviously error prone since the lock guard would be destroyed immediately after its construction, because it's a temporary (unnamed) object.

I was planning on doing something like this

struct Foo
{
    ~Foo() && = delete;
    ~Foo() & = default;
};

and get a compiler error if the type is constructed as a temporary.

1

There are 1 answers

3
ロウリン On

First, there must be only one destructor per class. Allowing ref-qualifiers on the destructor would make it possible to overload the destructor.

Another possible reason is to be consistent with const and volatile qualifiers:

A destructor shall not be declared const, volatile or const volatile (9.3.2). const and volatile semantics (7.1.5.1) are not applied on an object under destruction.

I guess, for consistency, distinguishing between rvalues and lvalues is not applied on an object under destruction.