C++ 如何将 std::string 转换为 const char* 或 char*?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/347949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a std::string to const char* or char*?
提问by user37875
How can I convert an std::string
to a char*
or a const char*
?
如何将 an 转换std::string
为 achar*
或 a const char*
?
回答by Johannes Schaub - litb
If you just want to pass a std::string
to a function that needs const char*
you can use
如果您只想将 a 传递给std::string
需要的函数,则const char*
可以使用
std::string str;
const char * c = str.c_str();
If you want to get a writable copy, like char *
, you can do that with this:
如果你想得到一个可写的副本,比如char *
,你可以这样做:
std::string str;
char * writable = new char[str.size() + 1];
std::copy(str.begin(), str.end(), writable);
writable[str.size()] = 'std::string str;
boost::scoped_array<char> writable(new char[str.size() + 1]);
std::copy(str.begin(), str.end(), writable.get());
writable[str.size()] = 'std::string str;
std::vector<char> writable(str.begin(), str.end());
writable.push_back('std::string x = "hello";
');
// get the char* using &writable[0] or &*writable.begin()
'; // don't forget the terminating 0
// get the char* using writable.get()
// memory is automatically freed if the smart pointer goes
// out of scope
'; // don't forget the terminating 0
// don't forget to free the string after finished using it
delete[] writable;
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.
编辑:请注意,上述内容不是异常安全的。如果new
调用和delete
调用之间有任何东西抛出,你将泄漏内存,因为没有任何东西会delete
自动调用你。有两种直接的方法可以解决这个问题。
boost::scoped_array
boost::scoped_array
boost::scoped_array
will delete the memory for you upon going out of scope:
boost::scoped_array
超出范围时将为您删除内存:
const char* p_c_str = x.c_str();
const char* p_data = x.data();
char* p_writable_data = x.data(); // for non-const x from C++17
const char* p_x0 = &x[0];
char* p_x0_rw = &x[0]; // compiles iff x is not const...
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::vector
,它完全为您管理内存。
char c = p[n]; // valid for n <= x.size()
// i.e. you can safely read the NUL at p[x.size()]
回答by Tony Delroy
Given say...
鉴于说...
p_writable_data[n] = c;
p_x0_rw[n] = c; // valid for n <= x.size() - 1
// i.e. don't overwrite the implementation maintained NUL
Getting a `char *` or `const char*` from a `string`
从 `string` 中获取 `char *` 或 `const char*`
How to get a character pointer that's valid while x
remains in scope and isn't modified further
如何获得一个有效的字符指针,同时x
保持在范围内并且不被进一步修改
C++11simplifies things; the following all give access to the same internal string buffer:
C++11简化了事情;以下所有内容都可以访问相同的内部字符串缓冲区:
// USING ANOTHER STRING - AUTO MEMORY MANAGEMENT, EXCEPTION SAFE
std::string old_x = x;
// - old_x will not be affected by subsequent modifications to x...
// - you can use `&old_x[0]` to get a writable char* to old_x's textual content
// - you can use resize() to reduce/expand the string
// - resizing isn't possible from within a function passed only the char* address
std::string old_x = x.c_str(); // old_x will terminate early if x embeds NUL
// Copies ASCIIZ data but could be less efficient as it needs to scan memory to
// find the NUL terminator indicating string length before allocating that amount
// of memory to copy into, or more efficient if it ends up allocating/copying a
// lot less content.
// Example, x == "abstd::string const cstr = { "..." };
char const * p = cstr.data(); // or .c_str()
cd" -> old_x == "ab".
// USING A VECTOR OF CHAR - AUTO, EXCEPTION SAFE, HINTS AT BINARY CONTENT, GUARANTEED CONTIGUOUS EVEN IN C++03
std::vector<char> old_x(x.data(), x.data() + x.size()); // without the NUL
std::vector<char> old_x(x.c_str(), x.c_str() + x.size() + 1); // with the NUL
// USING STACK WHERE MAXIMUM SIZE OF x IS KNOWN TO BE COMPILE-TIME CONSTANT "N"
// (a bit dangerous, as "known" things are sometimes wrong and often become wrong)
char y[N + 1];
strcpy(y, x.c_str());
// USING STACK WHERE UNEXPECTEDLY LONG x IS TRUNCATED (e.g. Hellostd::string str = { "..." };
char * p = str.data();
->Helstd::string str = { "..." };
str.c_str();
)
char y[N + 1];
strncpy(y, x.c_str(), N); // copy at most N, zero-padding if shorter
y[N] = 'std::string foo{"text"};
auto p = &*foo.begin();
'; // ensure NUL terminated
// USING THE STACK TO HANDLE x OF UNKNOWN (BUT SANE) LENGTH
char* y = alloca(x.size() + 1);
strcpy(y, x.c_str());
// USING THE STACK TO HANDLE x OF UNKNOWN LENGTH (NON-STANDARD GCC EXTENSION)
char y[x.size() + 1];
strcpy(y, x.c_str());
// USING new/delete HEAP MEMORY, MANUAL DEALLOC, NO INHERENT EXCEPTION SAFETY
char* y = new char[x.size() + 1];
strcpy(y, x.c_str());
// or as a one-liner: char* y = strcpy(new char[x.size() + 1], x.c_str());
// use y...
delete[] y; // make sure no break, return, throw or branching bypasses this
// USING new/delete HEAP MEMORY, SMART POINTER DEALLOCATION, EXCEPTION SAFE
// see boost shared_array usage in Johannes Schaub's answer
// USING malloc/free HEAP MEMORY, MANUAL DEALLOC, NO INHERENT EXCEPTION SAFETY
char* y = strdup(x.c_str());
// use y...
free(y);
All the above pointers will hold the same value- the address of the first character in the buffer. Even an empty string has a "first character in the buffer", because C++11 guarantees to always keep an extra NUL/0 terminator character after the explicitly assigned string content (e.g. std::string("this\0that", 9)
will have a buffer holding "this\0that\0"
).
所有上述指针将保持相同的值——缓冲区中第一个字符的地址。即使是空字符串也有“缓冲区中的第一个字符”,因为 C++11 保证在显式分配的字符串内容之后始终保留一个额外的 NUL/0 终止符(例如,std::string("this\0that", 9)
将有一个缓冲区持有"this\0that\0"
)。
Given any of the above pointers:
鉴于上述任何指针:
std::string foo{"text"};
std::vector<char> fcv(foo.data(), foo.data()+foo.size()+1u);
auto p = fcv.data();
Only for the non-const
pointer p_writable_data
and from &x[0]
:
仅适用于非const
指针p_writable_data
和 from &x[0]
:
std::string foo{"text"};
std::array<char, 5u> fca;
std::copy(foo.data(), foo.data()+foo.size()+1u, fca.begin());
Writing a NUL elsewhere in the string does notchange the string
's size()
; string
's are allowed to contain any number of NULs - they are given no special treatment by std::string
(same in C++03).
在字符串的其他地方写一个 NUL不会改变string
's size()
; string
允许包含任意数量的 NUL - 它们没有被给予特殊处理std::string
(在 C++03 中相同)。
In C++03, things were considerably more complicated (key differences highlighted):
在C++03 中,事情要复杂得多(突出显示了关键差异):
x.data()
- returns
const char*
to the string's internal buffer which wasn't required by the Standard to conclude with a NUL(i.e. might be['h', 'e', 'l', 'l', 'o']
followed by uninitialised or garbage values, with accidental accesses thereto having undefined behaviour).x.size()
characters are safe to read, i.e.x[0]
throughx[x.size() - 1]
- for empty strings, you're guaranteed some non-NULL pointer to which 0 can be safely added (hurray!), but you shouldn't dereference that pointer.
- returns
&x[0]
- for empty strings this has undefined behaviour(21.3.4)
- e.g. given
f(const char* p, size_t n) { if (n == 0) return; ...whatever... }
you mustn't callf(&x[0], x.size());
whenx.empty()
- just usef(x.data(), ...)
.
- e.g. given
- otherwise, as per
x.data()
but:- for non-
const
x
this yields a non-const
char*
pointer; you can overwrite string content
- for non-
- for empty strings this has undefined behaviour(21.3.4)
x.c_str()
- returns
const char*
to an ASCIIZ (NUL-terminated) representation of the value (i.e. ['h', 'e', 'l', 'l', 'o', '\0']). - although few if any implementations chose to do so, the C++03 Standard was worded to allow the string implementation the freedom to create a distinct NUL-terminated bufferon the fly, from the potentially non-NUL terminated buffer "exposed" by
x.data()
and&x[0]
x.size()
+ 1 characters are safe to read.- guaranteed safe even for empty strings (['\0']).
- returns
x.data()
- 返回
const char*
到标准不需要的字符串的内部缓冲区,以 NUL 结束(即可能['h', 'e', 'l', 'l', 'o']
后跟未初始化或垃圾值,意外访问具有未定义行为)。x.size()
字符可以安全读取,即x[0]
通过x[x.size() - 1]
- 对于空字符串,您可以保证一些非 NULL 指针可以安全地添加到其中 0(万岁!),但您不应该取消引用该指针。
- 返回
&x[0]
- 对于空字符串,这具有未定义的行为(21.3.4)
- 例如,鉴于
f(const char* p, size_t n) { if (n == 0) return; ...whatever... }
您不能f(&x[0], x.size());
在何时调用x.empty()
- 只需使用f(x.data(), ...)
.
- 例如,鉴于
- 否则,按照
x.data()
但:- 对于非
const
x
this 产生一个非const
char*
指针;您可以覆盖字符串内容
- 对于非
- 对于空字符串,这具有未定义的行为(21.3.4)
x.c_str()
- 返回值
const char*
的 ASCIIZ(以 NUL 结尾)表示(即 ['h', 'e', 'l', 'l', 'o', '\0'])。 - 虽然几乎没有实现选择这样做,在C ++ 03标准措辞,以允许字符串实现自由创造一个独特的NULL结尾的缓冲区上飞,从潜在非NUL终止缓冲由“暴露”
x.data()
和&x[0]
x.size()
+ 1 个字符可以安全阅读。- 即使对于空字符串 (['\0']) 也能保证安全。
- 返回值
Consequences of accessing outside legal indices
访问外部法律索引的后果
Whichever way you get a pointer, you must not access memory further along from the pointer than the characters guaranteed present in the descriptions above. Attempts to do so have undefined behaviour, with a very real chance of application crashes and garbage results even for reads, and additionally wholesale data, stack corruption and/or security vulnerabilities for writes.
无论采用哪种方式获取指针,都不得从指针开始访问内存,而不能比上述描述中保证出现的字符更远。尝试这样做有未定义的行为,即使读取也有非常真实的应用程序崩溃和垃圾结果的可能性,此外还有批发数据、堆栈损坏和/或写入的安全漏洞。
When do those pointers get invalidated?
这些指针什么时候失效?
If you call some string
member function that modifies the string
or reserves further capacity, any pointer values returned beforehand by any of the above methods are invalidated. You can use those methods again to get another pointer. (The rules are the same as for iterators into string
s).
如果您调用某个string
修改string
或保留更多容量的成员函数,则上述任何方法预先返回的任何指针值都将失效。您可以再次使用这些方法来获取另一个指针。(规则与迭代器相同string
)。
See also How to get a character pointer valid even after x
leaves scope or is modified furtherbelow....
另请参阅即使在x
离开范围或在下面进一步修改后如何使字符指针有效....
So, which is betterto use?
那么,哪个更好用呢?
From C++11, use .c_str()
for ASCIIZ data, and .data()
for "binary" data (explained further below).
从 C++11 开始,.c_str()
用于 ASCIIZ 数据和.data()
“二进制”数据(下面进一步解释)。
In C++03, use .c_str()
unless certain that .data()
is adequate, and prefer .data()
over &x[0]
as it's safe for empty strings....
在C ++ 03,使用.c_str()
除非肯定.data()
是足够的,而喜欢.data()
过&x[0]
,因为它是为空字符串安全....
...try to understand the program enough to use data()
when appropriate, or you'll probably make other mistakes...
...尝试充分理解该程序以data()
在适当的时候使用,否则您可能会犯其他错误...
The ASCII NUL '\0' character guaranteed by .c_str()
is used by many functions as a sentinel value denoting the end of relevant and safe-to-access data. This applies to both C++-only functions like say fstream::fstream(const char* filename, ...)
and shared-with-C functions like strchr()
, and printf()
.
由 保证的 ASCII NUL '\0' 字符.c_str()
被许多函数用作指示相关和安全访问数据结束的标记值。这适用于仅 C++ 的函数,如 sayfstream::fstream(const char* filename, ...)
和与 C 共享的函数,如strchr()
, 和printf()
。
Given C++03's .c_str()
's guarantees about the returned buffer are a super-set of .data()
's, you can always safely use .c_str()
, but people sometimes don't because:
鉴于 C++03.c_str()
对返回缓冲区的保证是's 的超集.data()
,您始终可以安全地使用.c_str()
,但人们有时不会这样做,因为:
- using
.data()
communicates to other programmers reading the source code that the data is not ASCIIZ (rather, you're using the string to store a block of data (which sometimes isn't even really textual)), or that you're passing it to another function that treats it as a block of "binary" data. This can be a crucial insight in ensuring that other programmers' code changes continue to handle the data properly. - C++03 only: there's a slight chance that your
string
implementation will need to do some extra memory allocation and/or data copying in order to prepare the NUL terminated buffer
- using
.data()
与阅读源代码的其他程序员通信,该数据不是 ASCIIZ(相反,您正在使用字符串来存储数据块(有时甚至不是真正的文本)),或者您将它传递给另一个将其视为“二进制”数据块的函数。在确保其他程序员的代码更改继续正确处理数据方面,这可能是一个至关重要的洞察力。 - 仅限 C++03:您的
string
实现有可能需要进行一些额外的内存分配和/或数据复制以准备 NUL 终止的缓冲区
As a further hint, if a function's parameters require the (const
) char*
but don't insist on getting x.size()
, the function probablyneeds an ASCIIZ input, so .c_str()
is a good choice (the function needs to know where the text terminates somehow, so if it's not a separate parameter it can only be a convention like a length-prefix or sentinel or some fixed expected length).
作为进一步的提示,如果函数的参数需要 ( const
)char*
但不坚持获取x.size()
,则该函数可能需要一个 ASCIIZ 输入,因此.c_str()
是一个不错的选择(该函数需要知道文本以某种方式终止的位置,因此如果不是一个单独的参数,它只能是一个约定,如长度前缀或标记或某些固定的预期长度)。
How to get a character pointer valid even after x
leaves scope or is modified further
即使在x
离开范围或进一步修改后如何使字符指针有效
You'll need to copythe contents of the string
x
to a new memory area outside x
. This external buffer could be in many places such as another string
or character array variable, it may or may not have a different lifetime than x
due to being in a different scope (e.g. namespace, global, static, heap, shared memory, memory mapped file).
您需要将的内容复制string
x
到 之外的新内存区域x
。此外部缓冲区可能位于许多地方,例如另一个string
或字符数组变量,x
由于处于不同的范围(例如命名空间、全局、静态、堆、共享内存、内存映射文件),它可能具有也可能没有不同的生命周期.
To copy the text from std::string x
into an independent character array:
将文本复制std::string x
到一个独立的字符数组中:
std::string foo{ "text" };
auto p = std::make_unique<char[]>(foo.size()+1u);
std::copy(foo.data(), foo.data() + foo.size() + 1u, &p[0]);
Other reasons to want a char*
or const char*
generated from a string
想要 achar*
或const char*
从 a 生成的其他原因string
So, above you've seen how to get a (const
) char*
, and how to make a copy of the text independent of the original string
, but what can you dowith it? A random smattering of examples...
所以,在上面您已经看到了如何获得 ( const
) char*
,以及如何制作独立于原始文本的文本副本string
,但是您可以用它做什么呢?一些随机的例子......
- give "C" code access to the C++
string
's text, as inprintf("x is '%s'", x.c_str());
- copy
x
's text to a buffer specified by your function's caller (e.g.strncpy(callers_buffer, callers_buffer_size, x.c_str())
), or volatile memory used for device I/O (e.g.for (const char* p = x.c_str(); *p; ++p) *p_device = *p;
) - append
x
's text to an character array already containing some ASCIIZ text (e.g.strcat(other_buffer, x.c_str())
) - be careful not to overrun the buffer (in many situations you may need to usestrncat
) - return a
const char*
orchar*
from a function (perhaps for historical reasons - client's using your existing API - or for C compatibility you don't want to return astd::string
, but do want to copy yourstring
's data somewhere for the caller)- be careful not to return a pointer that may be dereferenced by the caller after a local
string
variable to which that pointer pointed has left scope - some projects with shared objects compiled/linked for different
std::string
implementations (e.g. STLport and compiler-native) may pass data as ASCIIZ to avoid conflicts
- be careful not to return a pointer that may be dereferenced by the caller after a local
- 让“C”代码访问 C++
string
的文本,如printf("x is '%s'", x.c_str());
- 将
x
的文本复制到函数调用者指定的缓冲区(例如strncpy(callers_buffer, callers_buffer_size, x.c_str())
),或用于设备 I/O 的易失性内存(例如for (const char* p = x.c_str(); *p; ++p) *p_device = *p;
) - 将
x
的文本附加到已经包含一些 ASCIIZ 文本的字符数组(例如strcat(other_buffer, x.c_str())
) - 注意不要溢出缓冲区(在许多情况下您可能需要使用strncat
) - 返回 a
const char*
或char*
从函数(可能是由于历史原因 - 客户端使用您现有的 API - 或者为了 C 兼容性,您不想返回 astd::string
,但确实希望将您string
的数据复制到调用者的某处)- 注意不要在该指针指向的局部
string
变量离开作用域后返回可能被调用者取消引用的指针 - 某些具有为不同
std::string
实现(例如 STLport 和编译器原生)编译/链接的共享对象的项目可能会将数据作为 ASCIIZ 传递以避免冲突
- 注意不要在该指针指向的局部
回答by Mark Ransom
Use the .c_str()
method for const char *
.
将.c_str()
方法用于const char *
.
You can use &mystring[0]
to get a char *
pointer, but there are a couple of gotcha's: you won't necessarily get a zero terminated string, and you won't be able to change the string's size. You especially have to be careful not to add characters past the end of the string or you'll get a buffer overrun (and probable crash).
您可以使用&mystring[0]
来获取char *
指针,但有几个问题:您不一定会得到以零结尾的字符串,并且您将无法更改字符串的大小。您尤其必须注意不要在字符串末尾添加字符,否则会导致缓冲区溢出(并可能导致崩溃)。
There was no guarantee that all of the characters would be part of the same contiguous buffer until C++11, but in practice all known implementations of std::string
worked that way anyway; see Does “&s[0]” point to contiguous characters in a std::string?.
在 C++11 之前,不能保证所有字符都属于同一连续缓冲区的一部分,但实际上所有已知的实现都是这样std::string
工作的;请参阅“&s[0]”是否指向 std::string 中的连续字符?.
Note that many string
member functions will reallocate the internal buffer and invalidate any pointers you might have saved. Best to use them immediately and then discard.
请注意,许多string
成员函数将重新分配内部缓冲区并使您可能保存的任何指针无效。最好立即使用它们然后丢弃。
回答by Pixelchemist
C++17
C++17
C++17(upcoming standard) changes the synopsis of the template basic_string
adding a non const overload of data()
:
C++17(即将推出的标准)更改了模板的概要,basic_string
添加了一个非 const 重载data()
:
charT* data() noexcept;
Returns: A pointer p such that p + i == &operator for each i in [0,size()].
charT* data() noexcept;
返回: 一个指针 p 使得 p + i == &operator 对于 [0,size()] 中的每个 i。
CharT const *
from std::basic_string<CharT>
CharT const *
从 std::basic_string<CharT>
std::string foo{ "text" };
char * p = nullptr;
try
{
p = new char[foo.size() + 1u];
std::copy(foo.data(), foo.data() + foo.size() + 1u, p);
// handle stuff with p
delete[] p;
}
catch (...)
{
if (p) { delete[] p; }
throw;
}
CharT *
from std::basic_string<CharT>
CharT *
从 std::basic_string<CharT>
class DeepString
{
DeepString(const DeepString& other);
DeepString& operator=(const DeepString& other);
char* internal_;
public:
explicit DeepString( const string& toCopy):
internal_(new char[toCopy.size()+1])
{
strcpy(internal_,toCopy.c_str());
}
~DeepString() { delete[] internal_; }
char* str() const { return internal_; }
const char* c_str() const { return internal_; }
};
C++11
C++11
CharT const *
from std::basic_string<CharT>
CharT const *
从 std::basic_string<CharT>
void aFunctionAPI(char* input);
// other stuff
aFunctionAPI("Foo"); //this call is not safe. if the function modified the
//literal string the program will crash
std::string myFoo("Foo");
aFunctionAPI(myFoo.c_str()); //this is not compiling
aFunctionAPI(const_cast<char*>(myFoo.c_str())); //this is not safe std::string
//implement reference counting and
//it may change the value of other
//strings as well.
DeepString myDeepFoo(myFoo);
aFunctionAPI(myFoo.str()); //this is fine
CharT *
from std::basic_string<CharT>
CharT *
从 std::basic_string<CharT>
From C++11 onwards, the standard says:
从 C++11 开始,标准说:
- The char-like objects in a
basic_string
object shall be stored contiguously. That is, for anybasic_string
objects
, the identity&*(s.begin() + n) == &*s.begin() + n
shall hold for all values ofn
such that0 <= n < s.size()
.
const_reference operator[](size_type pos) const;
reference operator[](size_type pos);
Returns:
*(begin() + pos)
ifpos < size()
, otherwise a reference to an object of typeCharT
with valueCharT()
; the referenced value shall not be modified.
const charT* c_str() const noexcept;
const charT* data() const noexcept;
Returns: A pointer p such that
p + i == &operator[](i)
for eachi
in[0,size()]
.
- 对象中的类似字符的
basic_string
对象应连续存储。也就是说,对于任何basic_string
对象s
,身份&*(s.begin() + n) == &*s.begin() + n
应持的所有值n
这样0 <= n < s.size()
。
const_reference operator[](size_type pos) const;
reference operator[](size_type pos);
返回:
*(begin() + pos)
ifpos < size()
,否则是对类型CharT
为 value的对象的引用CharT()
;参考值不得修改。
const charT* c_str() const noexcept;
const charT* data() const noexcept;
返回: 一个指针 p 使得
p + i == &operator[](i)
对于每个i
in[0,size()]
。
There are severable possible ways to get a non const character pointer.
有多种可能的方法来获取非 const 字符指针。
1. Use the contiguous storage of C++11
1.使用C++11的连续存储
char* result = strcpy((char*)malloc(str.length()+1), str.c_str());
Pro
亲
- Simple and short
- Fast (only method with no copy involved)
- 简单而简短
- 快速(唯一不涉及复制的方法)
Cons
缺点
- Final
'\0'
is not to be altered / not necessarily part of the non-const memory.
- Final
'\0'
不可更改/不一定是非常量内存的一部分。
2. Use std::vector<CharT>
2. 使用 std::vector<CharT>
string str1("stackoverflow");
const char * str2 = str1.c_str();
Pro
亲
- Simple
- Automatic memory handling
- Dynamic
- 简单的
- 自动内存处理
- 动态的
Cons
缺点
- Requires string copy
- 需要字符串复制
3. Use std::array<CharT, N>
if N
is compile time constant (and small enough)
3. 使用std::array<CharT, N>
ifN
是编译时间常数(并且足够小)
std::string s(reinterpret_cast<const char *>(Data), Size);
Pro
亲
- Simple
- Stack memory handling
- 简单的
- 堆栈内存处理
Cons
缺点
- Static
- Requires string copy
- 静止的
- 需要字符串复制
4. Raw memory allocation with automatic storage deletion
4.具有自动存储删除的原始内存分配
##代码##Pro
亲
- Small memory footprint
- Automatic deletion
- Simple
- 内存占用小
- 自动删除
- 简单的
Cons
缺点
- Requires string copy
- Static (dynamic usage requires lots more code)
- Less features than vector or array
- 需要字符串复制
- 静态(动态使用需要更多代码)
- 比向量或数组更少的特征
5. Raw memory allocation with manual handling
5. 手动处理原始内存分配
##代码##Pro
亲
- Maximum 'control'
- 最大“控制”
Con
骗局
- Requires string copy
- Maximum liability / susceptibility for errors
- Complex
- 需要字符串复制
- 错误的最大责任/敏感性
- 复杂的
回答by Alessandro Teruzzi
I am working with an API with a lot of functions get as an input a char*
.
我正在使用具有很多功能的 API 作为输入 a char*
。
I have created a small class to face this kind of problem, I have implemented the RAII idiom.
我创建了一个小班来面对这种问题,我已经实现了 RAII 成语。
##代码##And you can use it as:
您可以将其用作:
##代码##I have called the class DeepString
because it is creating a deep and unique copy (the DeepString
is not copyable) of an existing string.
我已经调用了这个类,DeepString
因为它正在创建DeepString
一个现有字符串的深层和唯一副本(不可复制)。
回答by cegprakash
回答by devsaw
Just see this:
看看这个:
##代码##However, note that this will return a const char *
.
但是,请注意,这将返回一个const char *
.
For a char *
, use strcpy
to copy it into another char
array.
对于 a char *
,用于strcpy
将其复制到另一个char
数组中。
回答by anish
Try this
尝试这个
##代码##