c++ - 可变成员是否禁用非可变成员的常量优化?

标签 c++ constants mutable

据我所知,在 C++ 中,具有相同访问控制的结构/类成员按声明顺序存储在内存中。下一个例子 mc 应该一个接一个地存储吗:

#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 成员禁用了整个 structconst 优化(以某种方式使所有成员 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 the mutable class member even though the rest of the object is const.

[...]

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 a const 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/

相关文章:

c++ - 类型特征优化

c - 函数接受 const char * 但我需要向它传递一个 char*

c++ - shared_ptr<const A> 到 shared_pointer<A>

arrays - 奇怪的 ArrayBuffer 行为

c++ - 传递函数的缺点?

c++ - 写入二进制文件 block

c++静态变量初始化问题 - 引用另一个静态常量

c++ - grpc 的 ServerBuilder::AddListeningPort() 总是返回 TCP 端口零

c++ - 为什么operator[]有两个定义?

javascript - 如果是可变单元格,如何在 didReceiveAttrs Hook 中获取真实的 attr 值