c++ - const char* 作为参数传递时会自动删除吗?
问题描述
当我将 aconst char*
作为函数参数传递时(像这样):
void print(const char* text)
{
std::cout << text << std::endl;
}
会自动删除吗?如果没有,它会发生什么,我应该如何删除它?
解决方案
指针变量是指向其他内存的变量。
当您将指针作为参数传递给函数时,会复制指针本身,但不会复制它指向的内存。因此,没有什么可以“删除”。
让我们来看这个简单的示例程序:
#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.
推荐阅读
- nlp - 确定 NER 任务的迁移学习策略
- php - 使用php mysql显示数据时缺少Datatable.js搜索栏
- sql - 获取当月最后一个日期时输入参数值
- react-native - Redux-persist 没有更新状态
- python-2.7 - 石头剪刀布模拟的异常结果
- r - 我怎样才能转换这个特定的坐标?
- python - 查找日期是否存在的函数,如果存在则打印数据框的该行
- javascript - 在 React 中按标题对数据进行排序
- ios - 删除/处理 UINavigationBar UIAppearence 以修复在 Swift iOS 中点击更多后 UIActivityViewController 共享屏幕标题透明的问题
- azure - ListBox.SelectedItems 用于多个变量