且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++ reinterpret_cast - 这将总是工作正常吗?

更新时间:2023-11-08 10:56:34

数据成员的公共初始序列是不同的,并且C ++不能保证在这种情况下的布局,即使类型只有 const 资格。否则, union s的保证将有效地暗示,如果类型是标准布局类型,则它们需要具有公共布局(根据9.5 [class.union]

The common initial sequence of the data member is different and C++ makes no guarantee at all about the layout in this case, even if the types differ only by const qualification. Otherwise the guarantees for unions would effectively imply that the types need to have a common layout if they are standard-layout types (according to a note in 9.5 [class.union] paragraph 1).

在实践中,我期望这两种类型的布局是相同的,并且 reinterpret_cast 但是没有标准的保证。基于你的注释 MyStringConst 只保存一个指向字符串的指针,即,而不是转换为引用,我只是返回一个适当构造的 MyStringConst 并避免依赖未定义的行为:

In practice I would expect that the two types are laid out identical and that the reinterpret_cast works but there is no guarantee by the standard. Based on your comment MyStringConst merely holds a pointer to the string, i.e., instead of converting to references, I would just return a suitably constructed MyStringConst and avoid relying on undefined behavior:

MyString::operator MyStringConst() const {
    return MyStringConst(str, length);
}

MyString 仍然必须存活,只要转换的结果,但这与使用 reinterpret_cast 的情况没有不同。

The MyString object still has to live as long as the result from the conversion but this is no different to the case using reinterpret_cast.

BTW, hashCode 上的 volatile 是不明智的:唯一的效果是减慢程序。我想你正在尝试使用它来实现线程之间的同步,但在C ++ volatile 不能帮助你:在一个数据竞争当写成员在一个线程也在另一个线程中被不同步地访问。您会拼写成员

BTW, the volatile on the hashCode is ill-advised: the only effect it will have is to slow down the program. I guess you are trying to use it to achieve synchronization between threads but in C++ volatile doesn't help with that at all: you get a data race when writing the member in one thread it is also accessed unsynchronized in another thread. You'd spell the member

std::atomic<int> hashCode;