5.1.1/2 规定:
The keyword
this
names a pointer to the object for which a non-static member function (9.3.2) is invoked or a non-static data member’s initializer (9.2) is evaluated.
和:
Unlike the object expression in other contexts,
*this
is not required to be of complete type for purposes of class member access (5.2.5) outside the member function body.
以下代码打印8
:
#include <cstddef>
#include <iostream>
struct Test
{
std::size_t sz = sizeof(this->sz);
};
int main()
{
std::cout << Test{}.sz;
}
5.3.3 说:
The operand is either an expression, which is an unevaluated operand (Clause 5), or a parenthesized type-id. The
sizeof
operator shall not be applied to an expression that has function or incomplete type...
sizeof this->sz
具有相同的结果。
在这种情况下,this->
是否被视为空操作,它本质上等同于 sizeof(sz)
?
最佳答案
Is
this->
considered a no-op in this case and it's essentially equivalent tosizeof(sz)
?
没错。
this->sz
的类型是 std::size_t
,在该上下文中是一个完整的类型。
*this
的类型在这里不完整,但您引用了说明为什么这无关紧要的段落,我们可以直接分析 sz
特别是。
因此,this->
对表达式的语义没有实际影响,无论是好是坏。
正如 Sergey 所说,在一种情况下,使用 this->
进行成员访问会有所不同(模板库!),而这不是其中之一。
关于c++ - 这个大小是如何计算的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37278537/