简体   繁体   中英

where to place the pointer?

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.

So what do these do?

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.

Advice

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 .

How does one return (2)?

HEAP * getHeapPointer()
{
    HEAP * num = new HEAP;
    return num;
}

or simply,

HEAP * getHeapPointer()
{
    return new HEAP;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM