address-of operator return 变量引用的对象的地址

Does address-of operator return address of an object referenced by the variable

这是与 不同的问题,因为这里我使用的是对象类型 struct,而不是值 23...

我正在阅读 this chapter 关于指针的内容,其中说明如下:

The address of a variable can be obtained by preceding the name of a variable with an ampersand sign (&), known as address-of operator. For example:

MyStruct* myvar = new MyStruct();
&myvar; // what is this address?

我的理解是否正确,它是对象的地址 new MyStruct(),而不是变量本身?我还不太了解变量(不是它们引用的对象)是如何存储的,很可能在编译程序时根本没有使用它们。

Is my understanding correct that it's the address of an object new MyStruct(), not the variable itself?

不是,变量myvar的地址,用[=12]返回的对象初始化了 =].

根据您的,它不是...它是变量的地址myvar...

编辑

so the actual bytes of new Struct() are stored under different address than a variable?

new return 分配 struct 的 "bytes" 的内存地址。 myvar的值将是"bytes"在内存中的地址,&myvar是变量myvar在内存中的地址。

-------------------------------------------------------
|                     M E M O R Y                     |
-------------------------------------------------------
|   --------------                   ---------------  |
|   | myvar = 234| ----points to---> | new MyStruct|  |
|   --------------                   ---------------  |
|   ^                                ^                |
|   |                                |                |
|   address 1 (&myvar)               address 234      |
|                                                     |
-------------------------------------------------------

你得到的基本上是指针的副本you can prove it:

int* ptr = new int(2);
int& i = *ptr;
std::cout<<i<<std::endl; //prints 2
ptr = new int(3); //now ptr points to another address
std::cout<<*ptr<<std::endl; //prints 3
std::cout<<i<<std::endl; //still prints 2!

在这里忽略糟糕的内存管理,你会看到你只有一个引用,它是一个内存位置的副本。如果您更改原始指针,它不会改变。这是否回答了您的问题?