c++ - 这个大小是如何计算的?

标签 c++

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 to sizeof(sz)?

没错。

this->sz 的类型是 std::size_t,在该上下文中是一个完整的类型。

*this 的类型在这里完整,但您引用了说明为什么这无关紧要的段落,我们可以直接分析 sz 特别是。

因此,this-> 对表达式的语义没有实际影响,无论是好是坏。

正如 Sergey 所说,在一种情况下,使用 this-> 进行成员访问会有所不同(模板库!),而这不是其中之一。

关于c++ - 这个大小是如何计算的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37278537/

相关文章:

c++ - 错误无效使用 void 表达式。试图将参数传递给函数

c++ - 如何从函数返回多维 Mat 数组

c++ - rethrow_exception 真的可以抛出相同的异常对象,而不是一个拷贝吗?

c++ - Qt - 显示通过 QProcess 运行的 PowerShell 结果

C++ getline 在第一次调用后被跳过

c++ - 无法在 OpenGL 中绘制我的模型两次?

c++ - jpeg_decompress_struct 结构大小不匹配

c++ - 通过检测图像中的特定大对象或 Blob 来裁剪图像?

c++ - "CPU OpenCL Project"和 "GPU OpenCL Project"的区别

c++ - 为什么 C++ 中的析构函数以与初始化相反的顺序释放内存?