给定一个带有语句的函数 foo:
void foo() {
std::string * s;
}
此函数返回后是否回收内存?
我假设是,因为这个指针没有指向任何东西,但有些人说不——它是一个悬空指针。
给定一个带有语句的函数 foo:
void foo() {
std::string * s;
}
此函数返回后是否回收内存?
我假设是,因为这个指针没有指向任何东西,但有些人说不——它是一个悬空指针。
std::string* s
只是一个未初始化的指向字符串的指针。当函数 foo 返回时指针将被销毁(因为指针本身是分配在堆栈上的局部变量)。没有std::string
创建过,因此您不会有任何内存泄漏。
如果你说
void foo() {
std::string * s = new std::string;
}
然后你会有内存泄漏
This code is typical when people learn about strings a-la C, and then start using C++ through C idioms.
C++ classes (in particular standard library classes) treat objects as values, and manage themselves the memory they need.
std::string
, in this sense is not different from an int
. If you need a "text container", just declare an std::string (not std::string*
) and initialize it accordingly (uninitialized std::strings are empty by definition - and default constructor) than use it to form expression using method, operators and related functions like you will do with other simple types.
std::string* itself is a symptom of a bad designed environment.
Explicit dynamic memory in C++ is typically used in two situation:
Now, std:string manage itself the first point, and does not support the second (it has no virtual methods), so allocating it dynamically adds no value: it just adds all the complication to manage yourself the memory to contain the string object that is itself a manager of other memory to contain its actual text.
这段代码只是创建了一个指向内存中某处的指针,其中包含字符串值,它指向之前已分配的某个位置,它不分配新字符串。它只是为指针值分配内存,在函数返回后它不再有效......