string和char*的区别以及const_cast<>()

本文探讨了C++中使用const_cast对字符串常量进行操作的潜在风险及安全策略,包括数据修改的可能性、constness的重要性,并提供了一个安全的替代方案,通过复制字符串来避免直接修改原始字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

const_cast<char*>(Text.c_str())

#include<iostream>
#include<string>
#include<vector>
using namespace std;
 
void some_func( char * s)
{
     s[0] = 'X' ;
     cout<<s<<endl;
}
 
int main()
{
     string myStr = "hello" ;
     
     vector< char > str(myStr.begin(), myStr.end());
     str.push_back( '\0' );
 
     some_func(&str[0]);
 
     return 0;
}


Does the unpleasant C library function alter the data? If not, then simply
cast away the constness.

If it does, then you have to consider:

(1) Is it okay to alter the data at the address specified by c_str?

If so,

(1.a) Just cast away the constness and let it be altered.

If not,

(1.b) You'll have to make a copy.



The std::string manages it's own memory internally which is why, when it returns a pointer to that memory directly as it does with the c_str() function it makes sure it's constant so that your compiler will warn you if you try to do something incredibly silly like attempt to change it.


Using const_cast in that way literally casts away such safety and is only an arguably acceptable practice if you are  absolutely  sure that memory will not be modified. If you can't guarantee this then you must copy the string and use the copy; it's certainly a lot safer to do this in any event.

Here's a variation of 7stud's safe approach:.
Code:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <string>
#include <vector>
 
namespace
{
   char * GetNonConstStr( const std::string& s)
   {
   //return non-constant copy of s.c_str()
   static std::vector< char > var;
   var.assign(s.begin(),s.end());
   var.push_back( '\0' );
   return &var[0];
   }
   
   void someCFunction( char * str)
   {
     std::cout<<str<<std::endl;
   }
}
 
int main()
{
std::string s( "hello world" );
std::string t( "hello multiverse" );
 
someCFunction(GetNonConstStr(s));
someCFunction(GetNonConstStr(t));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值