A pointer is like a shortcut or a hyperlink. Creating just a shortcut does not install a program. Creating a hyperlink does not magically sets up the whole website.
Same with a pointer: a int*
is a pointer to an integer. It is not the integer itself. As such you must make sure that the pointer points to something meaningful before you try to follow the pointer.
One way of doing so is to create an integer and the sets a pointer to point to it:
int* ret_val = new int;
This will create an integer (the new
operator), and then sets the ret_val
pointer to point to it.
Objects created through new
exist until you explicitly destroy them through delete
or when your application ends. For that reason, if you have new int
in a function, it is safe to access it even if the function ends.
What would be dangereous, and probably caused your concern, is if you would set the pointer ret_val
not to a new integer, but to an existing local variable, i.e.
int myInteger;
int* ret_val = &myInteger;
In such scenario, ret_val
points to a local variable myInteger
which gets destroyed when the scope containing the declaration ends. You end up with a dangling pointer, referencing stuff that does not exist (think: broken hyperlink). Using such a pointer can lead to undefined behavior. It may crash your program, but it may as well silently accept it, modifying some random space in memory.
So, a function of the shape:
int* foo(void)
{
int* ret_val = new int;
*ret_val = 1234;
return ret_val;
}
is safe to use. It is not necessarily a good practice: the user of such function must know that it creates a new integer, that later - at some point - someone should delete
. Functions that do that typically highlight such behavior in some way, e.g. through its name. For example, allocateInt()
makes it clear that it created something that later should be delete. In contrast, getInt()
suggests that the integer already exists and nothing new is created.