C ++ const cast,不确定这是否安全 [英] C++ const cast, unsure if this is secure

查看:250
本文介绍了C ++ const cast,不确定这是否安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个愚蠢的问题,但我真的需要澄清这一点:

It maybe seems to be a silly question but i really need to clarify this:

这会给我的程序带来任何危险吗?

Will this bring any danger to my program?

是否需要 const_cast

如果我改变了输入指针的值地方会安全地用 std :: string 安全地工作,还是会创建未定义的行为?

If i change the input pointers values in place will it work safely with std::string or will it create undefined behaviour?

每当我修改输入指针并使其无法使用时,这可能会影响字符串some_text。

So far the only concern is that this could affect the string "some_text" whenever I modify the input pointer and makes it unusable.

std::string some_text = "Text with some input";

char * input = const_cast<char*>(some_text.c_str());

感谢给我一些提示,我想避免在自己的脚射击

Thanks for giving me some hints, i would like to avoid the shoot in my own foot

推荐答案

作为邪恶行为的一个例子:与gcc的Copy On Write实现交互。

As an example of evil behavior: the interaction with gcc's Copy On Write implementation.

#include <string>
#include <iostream>

int main() {
    std::string const original = "Hello, World!";
    std::string copy = original;

    char* c = const_cast<char*>(copy.c_str());
    c[0] = 'J';

    std::cout << original << "\n";
}

ideone


Jello,世界!

Jello, World!

问题?顾名思义,gcc的实现 std :: string 在覆盖下使用一个ref计数的共享缓冲区。当一个字符串被修改,实现将整齐地检查缓冲区是否共享,如果是,在修改之前复制它,确保共享此缓冲区的其他字符串不受新的写入影响(因此名称,

The issue ? As the name implies, gcc's implementation of std::string uses a ref-counted shared buffer under the cover. When a string is modified, the implementation will neatly check if the buffer is shared at the moment, and if it is, copy it before modifying it, ensuring that other strings sharing this buffer are not affected by the new write (thus the name, copy on write).

现在,使用你的邪恶程序,你通过const方法访问共享缓冲区(承诺不修改任何东西),但你要修改它!

Now, with your evil program, you access the shared buffer via a const-method (promising not to modify anything), but you do modify it!

请注意,对于MSVC的实现,它不使用Copy On Write,行为会不同(Hello,World! code>将正确打印)。

Note that with MSVC's implementation, which does not use Copy On Write, the behavior would be different ("Hello, World!" would be correctly printed).

这是未定义行为的本质。

这篇关于C ++ const cast,不确定这是否安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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