c++ - 对象初始化中是否允许指向 this 成员的指针?

标签 c++ initialization language-lawyer object-lifetime aggregate-initialization

来自Aggregate initialization, set pointer to struct member ,以下代码合法吗:

struct S 
{
  int a;
  int* aptr;
};

S s = { 3, &s.a };

最佳答案

引用最新标准草案:

[basic.scope.pdecl]

The point of declaration for a name is immediately after its complete declarator ([dcl.decl]) and before its initializer (if any), except as noted below.

所以,是的。标识符 s 已被声明,因此可以在其初始化程序中使用。

请注意,s 的值只有在初始化后才能使用。示例中未使用该值,因此这不是问题。

I'd also be curious about whether analogous code is valid when the two members of S are in reversed order

成员的顺序并不重要。

关于c++ - 对象初始化中是否允许指向 this 成员的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60191266/

相关文章:

c++ - g++ 线程局部变量是否遵循默认初始化规则?

c++ - C++初始化数组中的特定下标项

c++ - atomic_thread_fence(memory_order_release) 与使用 memory_order_acq_rel 有区别吗?

c++ - 将模板类型参数作为模板非类型参数的类型传递

c++ - 基于 2D 纹理的体绘制

C 编程 - 结构体中的整数值在赋值后变为 "random"

c++ - 读取 OpenCV Mat 16bit 到 QImage 8bit Greyscale

c++ - 解析模板类的专用静态成员变量的定义

c++ - 在 Qt 中处理临界区

c++ - 如何将 cin'd c 样式字符串传递给函数?