当我将 aconst char*
作为函数参数传递时(像这样):
void print(const char* text)
{
std::cout << text << std::endl;
}
会自动删除吗?如果没有,它会发生什么,我应该如何删除它?
当我将 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.
Nothing is automatically done in C++, because just like C the philosophy is "you don’t pay for what you don’t use". Everything must be done manually. Even if you see memory being automatically deallocated then that's because it's been done in the destructor (which you or the library writer need to write manually). For automatic variables on stack you just declare them and not allocate them manually so you also don't delete their memory region manually, the compiler will handle the allocation and deallocation
But when you call print("Hello World!")
then nothing needs to be deallocated because nothing has been allocated dynamically. A string literal like "Hello World!" is of type const char[N]
(and decays to const char*
when passing as parameters) and has static storage duration, which means they exist in memory for the whole life time of your program!
Only dynamically allocated memory needs to be freed