David KWH
David KWH

Reputation: 157

return type of decltype(*this)

I think I might have missed the subtlety in move construction because when I change the line Foo copy(*this); to decltype(*this) copy(*this);, I am thoroughly surprised by the output.

I checked it against, clang++-3.5 and g++-4.9, with the same behavior.

Would really appreciate a quick tip from the C++11 guru.

Update: Just forced the compiler to print the type of decltype(*this), it is actually a reference type i.e. Foo&.

class Foo {
    public: 
        Foo(int a): val(a) {}

        operator int() { return val; }

        auto& operator++() {
            val++;
            return *this;
        }

        auto operator++(int) {
            //Foo copy(*this);
            decltype(*this) copy(*this);
            ++(*this);
            return copy;
        }
    private:
        int val;
};

int main()
{
    Foo foo=1;
    cout << "foo++ = " << foo++ << "\n";
    cout << "foo++ = " << foo++ << "\n";
    cout << "foo = " << foo << "\n";

    return 0;
}

The output

foo++ = 2
foo++ = 3
foo = 3

Upvotes: 0

Views: 205

Answers (1)

AliciaBytes
AliciaBytes

Reputation: 7429

There seems to be a confusion as to why decltyp(*this) is Foo& and not Foo in your case. Firstly, think about dereferencing a pointer always resulting in a reference to the pointed to object.

temp = *ptr // this would work if dereferencing returned by value or by reference
*ptr = expr // this would only work if dereferencing results in a reference.

Now decltype(expr) always gives you exactly the same type as the expr. For you *this is of type Foo&.

If you want type deduction without it resulting in a reference use auto instead of decltype, so:

auto copy(*this);

instead of

decltype(*this) copy(*this);

Also I don't know why your question is talking about move construction so much as there is no move involved anywhere.

Upvotes: 2

Related Questions