2

给定一个带有语句的函数 foo:

void foo() {
  std::string * s;
}

此函数返回后是否回收内存?

我假设是,因为这个指针没有指向任何东西,但有些人说不——它是一个悬空指针。

4

3 回答 3

10

std::string* s只是一个未初始化的指向字符串的指针。当函数 foo 返回时指针将被销毁(因为指针本身是分配在堆栈上的局部变量)。没有std::string创建过,因此您不会有任何内存泄漏。

如果你说

void foo() {
    std::string * s = new std::string;
}

然后你会有内存泄漏

于 2013-01-31T05:07:02.023 回答
1

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:

  • You don't know at compile time the size of an object (typical with unknown size arrays, like C strings are)
  • You don't know at compile time the runtime-type of an object (since its class will be decided on execution, based on some other input)

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.

于 2013-01-31T09:01:15.550 回答
0

这段代码只是创建了一个指向内存中某处的指针,其中包含字符串值,它指向之前已分配的某个位置,它不分配新字符串。它只是为指针值分配内存,在函数返回后它不再有效......

于 2013-01-31T05:12:16.967 回答