How to copy/set a volatile std::string?

那年仲夏 提交于 2019-12-21 20:34:18

问题


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.


回答1:


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!"

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.

Hope this helps!



来源:https://stackoverflow.com/questions/19623434/how-to-copy-set-a-volatile-stdstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!