返回类型的decltype(* this)

时间:2015-07-09 01:33:36

标签: c++11 decltype

我想我可能已经错过了移动构造中的微妙之处,因为当我将行Foo copy(*this);更改为decltype(*this) copy(*this);时,我对输出完全感到惊讶。

我检查了它,clang ++ - 3.5和g ++ - 4.9,具有相同的行为。

非常感谢来自C ++ 11专家的快速提示。

更新:只是强制编译器打印decltype(*this)的类型,它实际上是一个引用类型,即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;
}

输出

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

1 个答案:

答案 0 :(得分:2)

在您的案例中,为什么decltyp(*this)Foo&而非Foo似乎存在混淆。首先,考虑取消引用指针总是导致对指向对象的引用。

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.

现在decltype(expr)始终为您提供与expr完全相同的类型。对于您*this类型为Foo&

如果你想要没有它的类型扣除导致引用使用auto而不是decltype,那么:

auto copy(*this);

而不是

decltype(*this) copy(*this);

此外,我不知道为什么你的问题正在讨论移动建设,因为任何地方都没有动作。

相关问题