简体   繁体   English

指针放在哪里?

[英]where to place the pointer?

what's the deffeence between using 使用之间的区别是什么

(1) HEAP num =* new HEAP (1) HEAP num =* new HEAP

(2) HEAP *num = new HEAP (2) HEAP *num = new HEAP

in c++. 在C ++中。 Also when writing a method how would one return an object if the they use (2)? 另外,在编写方法时,如果使用(2),该如何返回对象?

In C++ symbols often change meaning depending on their context. 在C ++中,符号经常根据上下文而改变含义。 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. 复制使用源* new HEAP构造自动变量 HEAP num ,这是一个HEAP ,其中* new HEAP是指向动态分配的 HEAP的指针,该指针立即由*运算符取消引用以获取其值。 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 . 初始化自动变量HEAP *num ,它是指向HEAP的指针,并带有指向动态分配的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. 避免使用此选项,因为它要求程序员通过在将来的某个时刻将其delete一次来手动管理分配的所有权 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 这是一个自动HEAP变量,因此您不必担心所有权或

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. 这是一个自动std::unique_ptr<HEAP>变量,该变量保存动态分配的HEAP并为您管理所有权。 Documentation for std::unique_ptr . std::unique_ptr文档

How does one return (2)? 一个人如何返回(2)?

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

or simply, 或者简单地说,

HEAP * getHeapPointer()
{
    return new HEAP;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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