0

相关问题:模板功能在模板类中相同

我对指针“this”(gcc 4.7.2,c++11)的类型有点不安。原则上,例如C类型的非常量对象的指针“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.2 this指针[class.this]

1 - [...]关键字this是prvalue表达式,其值是调用函数的对象的地址。类的this成员函数中的类型XX*

this不是const左值,它是纯右值表达式,所以它不需要是const. 你不能分配给它,因为它是一个纯右值,同样的原因你不能写2 + 2 = 5.

于 2012-12-12T15:28:15.493 回答
2

在这种情况下,类型thisC *

9.3.2 this指针[class.this]

在非静态 (9.3) 成员函数的主体中,关键字 this 是一个纯右值表达式,其值是调用该函数的对象的地址。类 X 的成员函数中 this 的类型是 X*。

...

没有提到 forX *const等。this指针是一个prvalue,这就是为什么它不能被分配给它,而不是因为它是 const 限定的。

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 回答