Tim*_*eaf 7 c++ string memory-management string-literals
所以,我想更好地掌握C++中的字符串文字是如何工作的.我主要关注的是你将字符串文字的地址分配给指针并传递它的情况.例如:
char* advice = "Don't stick your hands in the toaster.";
Run Code Online (Sandbox Code Playgroud)
现在让我说我只是通过在程序的持续时间内复制指针来传递这个字符串.当然,这可能不是一个好主意,但我很好奇幕后会发生什么.
再举一个例子,假设我们创建一个返回字符串文字的函数:
char* foo()
{
// function does does stuff
return "Yikes!"; // somebody's feeble attempt at an error message
}
Run Code Online (Sandbox Code Playgroud)
现在让我们说这个函数经常调用,字符串文字只用了大约一半的时间:
// situation #1: it's just randomly called without heed to the return value
foo();
// situation #2: the returned string is kept and used for who knows how long
char* retVal = foo();
Run Code Online (Sandbox Code Playgroud)
在第一种情况下,实际发生了什么?字符串刚刚创建但未使用,并且从未取消分配?
在第二种情况下,只要用户发现需要它,字符串是否会被维护?当不再需要它时会发生什么......那个存储器会被释放(假设没有任何东西指向那个空间)?
不要误解我的意思,我不打算像这样使用字符串文字.我打算使用容器来检查我的字符串(可能是std :: string).我大多只是想知道这些情况是否会导致内存管理或数据损坏的问题.
GMa*_*ckG 22
字符串文字具有类型const char[N](其中N长度为+ 1)并且是静态分配的.你不必担心内存问题; 如果你的程序中使用了一个字符串,它将全部为你处理,并驻留在程序存储器中的某个地方(通常是只读的).
也就是说,这些是"相同的":
static const char str[] = "a string";
"a string"
Run Code Online (Sandbox Code Playgroud)
当您指向字符串文字时,您指向数组中的第一个字符.事实上,因为类型是const char[],通过它指向它是唯一安全的const char*.从字符串文字转换char*为不推荐使用,并且不安全.
// the "same"
static const char str[] = "a string";
const char* strPtr = str; // decays
const char* s1 = "a string";
char* s2 = "a string"; // allowed, implicit const_cast
*s1 = 'A'; // not allowed, it's const
*s2 = 'B'; // allowed, it's not const (but leads to undefined behavior)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2548 次 |
| 最近记录: |