When I pass a const char*
as a function argument (like this):
void print(const char* text)
{
std::cout << text << std::endl;
}
Is it automatically deleted? If not, what happens to it, and how should I delete it?
When I pass a const char*
as a function argument (like this):
void print(const char* text)
{
std::cout << text << std::endl;
}
Is it automatically deleted? If not, what happens to it, and how should I delete it?
A pointer variable is a variable that is pointing to some other memory.
When you pass a pointer as argument to a function, the pointer itself is copied, but not the memory it is pointing to. Therefore there's nothing to "delete".
Lets take this simple example program:
#include <iostream>
void print(const char* text)
{
std::cout << text << std::endl;
}
int main()
{
const char* text = "foobar";
print(text);
}
When the main
function is running you have something like this:
+-----------------------+ +----------+ | text in main function | --> | "foobar" | +-----------------------+ +----------+
Then when the print
function is called and running it have its own copy of the pointer:
+-----------------------+ | 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