gpt4 book ai didi

c++ - 指向不完整类型数据成员的指针

转载 作者:可可西里 更新时间:2023-11-01 18:36:43 27 4
gpt4 key购买 nike

以下代码在 C++ 中是否定义明确? (*)

我很难弄清楚该从哪里看标准,而且在网络上搜索也没有找到任何具体的内容。

struct S;
struct T {
constexpr T() = default;
bool S::* a = nullptr;
int b = 42;
};
const T t{};
// Test. Compiled using: cl /W4 /WX /FAs filename.cpp
#include <stdlib.h>
int main() {
if (t.b != 42) abort();
}

我问的原因是因为它适用于(或似乎适用于)较新版本的 GCC 和 Clang (x86/x86_64),但在 Visual Studio 2015 Update 2 和 Update 3 RC 中失败(**)。

在报告错误之前,我想确定我没有依赖未定义的行为或只是没有搜索正确的术语。

我还尝试使用 /vmg/vmb,如 this post 中所述.

(*):我主要关心 C++14 及更高版本,但我看不出任何理由不适用于 C++11。
(**):如果代码定义明确,它看起来像是代码生成错误,其中没有为指针分配空间。将 struct S 更改为 struct S{} 似乎使代码“有效”。

最佳答案

您的代码定义明确:

N4594 3.2/5

[...]A class type T must be complete if:

  • (5.1) an object of type T is defined (3.1), or
  • (5.2) a non-static class data member of type T is declared (9.2), or
  • (5.3) T is used as the object type or array element type in a new-expression (5.3.4), or
  • (5.4) an lvalue-to-rvalue conversion is applied to a glvalue referring to an object of type T (4.1), or
  • (5.5) an expression is converted (either implicitly or explicitly) to type T (Clause 4, 5.2.3, 5.2.7, 5.2.9, 5.4), or
  • (5.6) an expression that is not a null pointer constant, and has type other than cv void*, is converted to the type pointer to T or reference to T using a standard conversion (Clause 4), a dynamic_cast (5.2.7) or a static_cast (5.2.9), or
  • (5.7) a class member access operator is applied to an expression of type T (5.2.5), or
  • (5.8) the typeid operator (5.2.8) or the sizeof operator (5.3.3) is applied to an operand of type T, or
  • (5.9) a function with a return type or argument type of type T is defined (3.1) or called (5.2.2), or
  • (5.10) a class with a base class of type T is defined (Clause 10), or
  • (5.11) an lvalue of type T is assigned to (5.18), or
  • (5.12) the type T is the subject of an alignof expression (5.3.6), or
  • (5.13) an exception-declaration has type T, reference to T, or pointer to T (15.3).

他们都没有说 T 需要完整才能声明 Tpointer-to-member

关于c++ - 指向不完整类型数据成员的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37999741/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com