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

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

问题描述

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

How can I convert an std::string to a char* or a 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 调用之间的任何内容抛出,您将泄漏内存,因为没有任何东西会自动为您调用 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

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天全站免登陆