如何将std :: string转换为const char *或char *? [英] How to convert a std::string to const char* or char*?

查看:268
本文介绍了如何将std :: string转换为const char *或char *?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 std :: string 转换为 char * const char *

推荐答案

如果你只想传递 std :: string 到需要 const char * 您可以使用

If you just want to pass a std::string to a function that needs const char* you can use

std::string str;
const char * c = str.c_str();

如果要获得可写副本,例如 char * ,你可以这样做:

If you want to get a writable copy, like char *, you can do that with this:

std::string str;
char * writable = new char[str.size() + 1];
std::copy(str.begin(), str.end(), writable);
writable[str.size()] = '\0'; // don't forget the terminating 0

// don't forget to free the string after finished using it
delete[] writable;

编辑:请注意,上述操作不是例外安全的。如果 new 调用和 delete 调用throws之间的任何内容,你将泄漏内存,因为没有什么会调用 delete 。有两种直接的方法来解决这个问题。

Edit: Notice that the above is not exception safe. If anything between the new call and the delete call throws, you will leak memory, as nothing will call delete for you automatically. There are two immediate ways to solve this.

boost :: scoped_array 将会在您退出作用域时删除您的内存:

boost::scoped_array will delete the memory for you upon going out of scope:

std::string str;
boost::scoped_array<char> writable(new char[str.size() + 1]);
std::copy(str.begin(), str.end(), writable.get());
writable[str.size()] = '\0'; // don't forget the terminating 0

// get the char* using writable.get()

// memory is automatically freed if the smart pointer goes 
// out of scope



std :: vector



这是标准方式(不需要任何外部库)。您使用 std :: vector ,它完全为你管理内存。

std::vector

This is the standard way (does not require any external library). You use std::vector, which completely manages the memory for you.

std::string str;
std::vector<char> writable(str.begin(), str.end());
writable.push_back('\0');

// get the char* using &writable[0] or &*writable.begin()

这篇关于如何将std :: string转换为const char *或char *?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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