0

関連する質問:template-function-is-same-in-template-classes

ポインタのタイプ「this」(gcc 4.7.2、c ++ 11)に少し戸惑っています。原則として、たとえばタイプCの非constオブジェクトのポインタ「this」のタイプは「C * const」であるため、「*this」のタイプは「C」です。しかし、「is_same」クラスの動作は私を混乱させました。

テスト:

// this-type.cpp
#include <iostream>
#include <type_traits>

using namespace std;

class C
{
public:
   void test()
   {
       cout << boolalpha;

       cout << "'this' const?" << "              "
            << is_const<decltype(this)>::value << endl;

       cout << "'*this' const?" << "             "
            << is_const<decltype(*this)>::value << endl;

       cout << "'*this' and 'C' the same?" << "  "
            << is_same<decltype(*this), C>::value << endl;

       cout << "'this' and 'C*' the same?" << "  "
            << is_same<decltype(this), C*>::value << endl;
   }
};

int main()
{
    C c;

    c.test();
}

出力:

$ g++ --version | grep g++
g++ (Ubuntu/Linaro 4.7.2-2ubuntu1) 4.7.2
$ g++ -std=c++11 this-type.cpp
$ ./a.out
'this' const?              false
'*this' const?             false
'*this' and 'C' the same?  false
'this' and 'C*' the same?  true

ただし、期待される出力は次のとおりです。

$./a.out
'this' const?              true   // C* const
'*this' const?             false  // C
'*this' and 'C' the same?  true
'this' and 'C*' the same?  false  // C* const vs. C*

ここで何が起こったのですか?

4

2 に答える 2

3

9.3.2thisポインタ[class.this]

1-[...]キーワードthisは、関数が呼び出されるオブジェクトのアドレスを値とするprvalue式です。thisクラスのメンバー関数のタイプXはですX*

thisは左辺値ではなく、const前値式であるため、である必要はありませんconst。それはprvalueであるため、割り当てることはできません。これは、書くことができないのと同じ理由です2 + 2 = 5

于 2012-12-12T15:28:15.493 に答える
2

この場合、のタイプthisC *

9.3.2thisポインタ[class.this]

非静的(9.3)メンバー関数の本体では、キーワードthisは、関数が呼び出されるオブジェクトのアドレスを値とするprvalue式です。クラスXのメンバー関数でのこのタイプはX*です。

..。

X *constなどについては言及されていません。thisポインタはprvalueであるため、const-qualifiedのためではなく、割り当てることができません。

PS。ちなみにそうですね

C *p; // for any type C
is_same<declype (*p), C &>::value == true

is_sameただし、標準では次のように記述されているため、実装(コンパイラまたは)のアーティファクトである可能性があります。

5.3.1単項演算子[expr.unary.op]

1..。

...式のタイプが「Tへのポインター」の場合、結果のタイプは「T」です。..。

于 2012-12-12T15:29:17.767 に答える