C++ Notes: Return Pointer or Reference
Explaination
A pointer or reference could not be return if they point/refer to a local variable stored in stack inside a function (local variable stored in stack will be destoried automatically when return, and the pointer become wild
)
Situations when a function could return pointer or reference
- variable defined outside a function scope
- global variable
- local static variable
- local variable stored in heap (
new
opterator,malloc()
)
Other process could not access the memory of variable stored in heap until it is released. That’s why.
Example
|
|
Return *this
, or alrealy exist objets
|
|
What’s the defference between new
and malloc()
malloc()
is a function that takes a number (of bytes) as its argument; it __returns a void*__ pointing to unitialized storage.new
is an operator that **takes a type** and (optionally) a set of initializers for that type as its arguments; it **returns a pointer to an** (optionally) initialized **object of its type**.
The difference is most obvious when you want to allocate an object of a user-defined type with non-trivial initialization semantics