如何复制/设置易失性 std::string? [英] How to copy/set a volatile std::string?

查看:25
本文介绍了如何复制/设置易失性 std::string?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何复制volatile std::string?没有用于 volatile 的复制构造函数,也不允许像 c_str 这样的东西允许 volatile 访问.operator= 似乎也不允许设置 volatile.看起来 std::string 根本无法用作易失性对象.这是有意为之,还是我缺少某种使用方法?

How can I copy a volatile std::string? There is no copy constructor for volatile, nor does something like c_str allow volatile access. operator= also doesn't seem to allow setting a volatile. It seems like std::string is simply unusable as a volatile object. Is this intended, or am I missing some way to use it?

注意:我有简单的解决方法,我只是在尝试在一些低级代码中使用字符串时遇到了这个问题.

NOTE: I have easy workarounds, I just came upon the issue while trying to use string in some low-level code.

推荐答案

如您所见,std::string 上的所有成员函数都没有标记为 volatile,因此您不能对 volatile std::string 执行任何操作.我认为唯一的选择是抛弃 volatileness 并对结果执行操作,如下所示:

As you noted, none of the member functions on std::string are marked volatile, so you can't perform any operations on a volatile std::string. I think the only option would be to cast away volatileness and perform operations on the result, as shown here:

const_cast<std::string&>(myVolatileString) = "Now I'm different!"

不过,从根本上说,您可能不应该制作 volatile std::string.volatile 适用于可能被外部源改变或被多线程改变的对象.第一种情况非常不寻常,需要一些非常特殊的硬件来了解 std::string 的布局.第二个是不安全的,因为 std::string 不是线程安全的.

Fundamentally, though, you probably shouldn't be making a volatile std::string. volatile is appropriate for objects that might be mutated by external sources or changed by multiple threads. This first case is pretty unusual and would require some very special hardware that knew the layout of std::string. The second is unsafe because std::string isn't thread-safe.

希望这会有所帮助!

这篇关于如何复制/设置易失性 std::string?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆