Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't a destructor have reference qualifiers?

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.

like image 736
Timo Avatar asked Feb 28 '20 08:02

Timo


1 Answers

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.

like image 171
ネロク・ゴ Avatar answered Sep 29 '22 12:09

ネロク・ゴ