Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In-place destruction on type with overloaded operator->

Suppose some type Foo has an overloaded operator-> that returns a Bar*:

struct Foo
{
    Bar* operator->();
};

If I want to destruct the returned Bar instance in-place from within the Foo class, can I write the following?

this->~Bar();

g++ does not like that code. It works if I write this:

(*this)->~Bar();

Does the "rescursive forwarding rule" not apply in this case? Why not?

like image 493
fredoverflow Avatar asked Jan 26 '26 05:01

fredoverflow


2 Answers

Here is the rule for chaining ->, found in 13.5.6 [over.ref] of the standard:

An expression x->m is interpreted as (x.operator->())->m for a class object x of type T if T::operator->() exists and if the operator is selected as the best match function by the overload resolution mechanism (13.3).

Since this is a pointer, not a class object, it doesn't apply.

Instead, this rule in 5.2.5 ([expr.ref]) is applicable:

For the second option (arrow) the first expression shall have pointer to complete class type. The expression E1->E2 is converted to the equivalent form (*(E1)).E2; the remainder of 5.2.5 will address only the first option (dot).

like image 142
Ben Voigt Avatar answered Jan 28 '26 19:01

Ben Voigt


Because this is a pointer and not a reference and -> for a pointer doesn't have a return value for forwarding to take place on. Consider equivalently

shared_ptr<std::string>* ptr = // some init
ptr->push_back('0'); // error
like image 38
Puppy Avatar answered Jan 28 '26 19:01

Puppy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!