据我所知,在 C++ 中,具有相同访问控制的结构/类成员按声明顺序存储在内存中。下一个例子 m
和 c
应该一个接一个地存储吗:
#include <cstdlib>
#include <iostream>
struct X
{
mutable int m;
int c;
};
const X cx = {0, 1};
int main()
{
X& x = const_cast<X&>(cx);
x.m = rand();
x.c = rand();
std::cout<<x.m<<" "<<x.c;
}
在此示例中,程序运行并打印 2 个随机数。如果我删除 mutable
它会崩溃,因为 cx
存储在只读保护内存中。
这让我想知道 - 是否有一个 mutable
成员禁用了整个 struct
的 const
优化(以某种方式使所有成员 mutable
)?
是否可以将 struct
的一部分存储在只读内存中,将其他部分存储在非只读内存中,并遵守 C++ 标准内存布局?
这是在 Windows 7 上使用 Visual Studio 2010 和在 Ubuntu 上使用 GCC 4.7.2 测试的。
最佳答案
该标准在很多地方都谈到了 mutable
成员。我在下面引用了标准的三个部分,解释了您只能修改 const
对象的 mutable
成员。否则就是未定义的行为。
3.9.3 CV-qualifiers [basic.type.qualifier]
A const object is an object of type
const T
or a non-mutable subobject of such an object.[...]
7.1.1 Storage class specifiers [dcl.stc]
The
mutable
specifier on a class data member nullifies a const specifier applied to the containing class object and permits modification of themutable
class member even though the rest of the object isconst
.[...]
7.1.6.1 The cv-qualifiers [dcl.type.cv]
Except that any class member declared
mutable
(7.1.1) can be modified, any attempt to modify aconst
object during its lifetime (3.8) results in undefined behavior.
Is it possible to store parts of a
struct
in readonly memory and other parts on non-readonly memory and respect C++ standard memory layout?
不,不可能将 struct
(或 class
)的一部分与对象的其余部分存储在不同的内存区域中。
关于c++ - 可变成员是否禁用非可变成员的常量优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18586189/