首页 > 解决方案 > const char* 作为参数传递时会自动删除吗?

问题描述

当我将 aconst char*作为函数参数传递时(像这样):

void print(const char* text)
{
     std::cout << text << std::endl;
}

会自动删除吗?如果没有,它会发生什么,我应该如何删除它?

标签: c++pointersmemory-managementstring-literalsconst-char

解决方案


指针变量是指向其他内存的变量。

当您将指针作为参数传递给函数时,会复制指针本身,但不会复制它指向的内存。因此,没有什么可以“删除”。


让我们来看这个简单的示例程序:

#include <iostream>

void print(const char* text)
{
     std::cout << text << std::endl;
}

int main()
{
    const char* text = "foobar";

    print(text);
}

main函数运行时,你有这样的东西:

+------------------------+ +------------+
| 主函数中的文本 | --> | “富吧” |
+------------------------+ +------------+

然后当print函数被调用并运行时,它有自己的指针副本:

+-----------------------+
| text in main function | -\
+-----------------------+   \      +----------+
                              >--> | "foobar" |
+------------------------+   /     +----------+
| text in print function | -/
+------------------------+

Two variables pointing to the same memory.

Furthermore, literal strings like "foobar" in the example above will never need to be deleted or free'd, they are managed by the compiler and lives throughout the entire run-time of the program.


推荐阅读