我可以const_cast c_str()如果字符串是const? [英] Can I const_cast c_str() if the string is const?

查看:130
本文介绍了我可以const_cast c_str()如果字符串是const?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了很多堆栈溢出的例子,但是这些例子是基于非const std :: string。如果字符串是const(顶层和非顶层),如果是什么?

I have found a lot of examples from stack overflow, but those examples are based on non-const std::string. What if the string is const(top level and non top level)?

std::string encrypt(std::string const &input)
{
  //do something, ArrayGuard is a smart pointer to guard the raw char* delete by free
  ArrayGuard<char> guard(encrypt_str(const_cast<char*>(input.c_str())));

  return std::string(guard.get(), std::strlen(guard.get()));    
}

case 1(非顶级?):

case 1(non top level?) :

std::string input = "abcde";
std::string encrypt_password = encrypt(input);

案例2(顶层?):

std::string const input = "abcde";
std::string encrypt_password = encrypt(input);

确定,encrypt_str > alter char *我传入它(如果可以,我想请求他们修复这个非const修正api)。

I am sure that the encrypt_str would not alter the char* I pass into it(if it is possible, I would like to ask them to fix this non const correction api).

ps:我不是确保我完全理解什么是顶级const /& /&&& / volatile,这就是为什么我把?后面

ps : I am not sure that I am fully understanding what is top level const/&/&&/volatile, that is why I put "?" behind the case

推荐答案

您必须注意的有关 const_cast 是如果你使用它来修改最初声明为 const 的对象,那么你会得到未定义的行为。

The rule you have to watch out for regarding const_cast is that if you use it to modify an object that was originally declared as const, then you get undefined behaviour.

std :: string

The constness of the std::string doesn't make any difference. Even if the std::string is not const, the c_str function still returns a const char*. Nothing changes when you make the std::string const.

这篇关于我可以const_cast c_str()如果字符串是const?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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