gpt4 book ai didi

c++ - 为什么带有引用的类不遵守标准布局?

转载 作者:IT老高 更新时间:2023-10-28 13:03:06 25 4
gpt4 key购买 nike

执行以下代码:

#include <iostream>
#include <type_traits>

struct s_ref {
int &foo;
};

struct s_ptr {
int *foo;
};

int main(int argc, char *argv[])
{
std::cout << "s_ref is_standard_layout:" << std::is_standard_layout<struct s_ref>::value << std::endl;
std::cout << "s_ptr is_standard_layout:" << std::is_standard_layout<struct s_ptr>::value << std::endl;
return 0;
}

结果:

s_ref is_standard_layout:0
s_ptr is_standard_layout:1

基于标准布局的使用(即:“标准布局类型对于与用其他编程语言编写的代码进行通信很有用”)这是有道理的,但我不确定违反了哪个规则:

A standard-layout class is a class (defined with class, struct orunion) that:

  • has no virtual functions and no virtual base classes.

  • has the same access control (private, protected, public) for all its non-static data members.

  • either has no non-static data members in the most derived class and at most one base class with non-static data members, or has nobase classes with non-static data members.

  • its base class (if any) is itself also a standard-layout class.

  • And, has no base classes of the same type as its first non-static datamember.

编辑:引用来自:http://www.cplusplus.com/reference/type_traits/is_standard_layout/ , 但是 http://en.cppreference.com/w/cpp/concept/StandardLayoutType也是类似的。

最佳答案

C++ 标准的标准布局类概念的要点是,此类类的实例可以作为字节可靠地访问或复制到字节,正如 C++11 标准所指出的那样在其第 9/9 节中,创建了这样一个类

useful for communicating with code written in other programming languages

但是,C++ 标准根本不需要引用来使用存储。它不是一个对象。你不能拿它的地址。所以它不能(可靠地)复制到字节,或作为字节访问。因此它与标准布局类的概念不兼容。

在正式场合,

C++11 §9/7:

A standard-layout class is a class that:
— has no non-static data members of type non-standard-layout class (or array of such types) or reference,

关于c++ - 为什么带有引用的类不遵守标准布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36354041/

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