what's the deffeence between using
(1) HEAP num =* new HEAP
(2) HEAP *num = new HEAP
in c++. Also when writing a method how would one return an object if the they use (2)?
what's the deffeence between using
(1) HEAP num =* new HEAP
(2) HEAP *num = new HEAP
in c++. Also when writing a method how would one return an object if the they use (2)?
In C++ symbols often change meaning depending on their context. In
HEAP num =* new HEAP
the *
is the dereference operator. This gets the value of an object from a pointer. *
In
HEAP *num = new HEAP
*
is not an operator, it is part of the type denoting that the variable is a pointer.
*
is also used as the multiplication operator. Note that *
can be overloaded to do anything the programmer wants it to do, but this should be reserved for multiplication-and-dereferencing-like behaviours to to prevent confusion.
HEAP num =* new HEAP
Copy constructs Automatic variable HEAP num
, which is a HEAP
, with source * new HEAP
where * new HEAP
is a pointer to a Dynamically allocated HEAP
that is promptly dereferenced with the *
operator to get its value. Do not use this option because no pointer is kept to the dynamic allocation making it close to impossible to free. This is a memory leak.
HEAP *num = new HEAP
Initializes Automatically variable HEAP *num
, which is a pointer to a HEAP
, with a pointer to a Dynamically allocated HEAP
. Avoid using this option because it requires the programmer to manually manage the ownership of the allocation by delete
ing it exactly once at some point in the future. It is surprising how difficult such a simple-sounding thing can be to get right.
Prefer
HEAP num;
which is an Automatic HEAP
variable so you do not have to worry about ownership or
std::unique_ptr<HEAP> num = std::make_unique<HEAP>();
which is an Automatic std::unique_ptr<HEAP>
variable that holds a Dynamically allocated HEAP
and manages the ownership for you. Documentation for std::unique_ptr
.
HEAP * getHeapPointer()
{
HEAP * num = new HEAP;
return num;
}
or simply,
HEAP * getHeapPointer()
{
return new HEAP;
}