std::unique_ptr::get 和 operator& 的不同地址

1 c++ pointers smart-pointers unique-ptr

在下面的例子中使用指针让我感到困惑,所以我可能误解了一些东西。我将尝试展示我的理解方式和一些伪简单的例子。

创建std::unique_ptr名称变量my_int确保它不能被复制,并且它的int对象只有一个所有者。然后我创建一个向量来存储指针并将其放入而不用std::emplace_back(). 现在我想检查 vector 的元素integers[0]在内存中是否与原始元素具有相同的地址my_int。我认为应该是因为无法复制此元素。

示例代码:

auto my_int = std::make_unique<int>(1);
std::vector<std::unique_ptr<int>> integers;
integers.emplace_back(my_int.get());

std::cout<< "Value of my_int: " << *my_int << std::endl;
std::cout << "Address of my_int: " << my_int.get() << std::endl;
std::cout << "Also address of my_int: " << &my_int << std::endl;
std::cout << "Also address of my_int: " << &integers[0]<< std::endl;
std::cout << "Also address of my_int: " << integers[0].get()<< std::endl;
Run Code Online (Sandbox Code Playgroud)

测试结果:

Value of my_int: 1
Address of my_int: 0x260fc40
Also address of my_int: 0x65fb58
Also address of my_int: 0x260fe20
Also address of my_int: 0x260fc40
Run Code Online (Sandbox Code Playgroud)

我也尝试std::move()在将对象放入向量时使用但效果相同,地址不同但我不明白为什么。

我的第一个困惑是&my_intmy_int.get()不一样,第二个困惑是也integers[0].get()不同于&integers[0]

Som*_*ude 6

该表达式my_int.get()返回一个指向所包含整数的指针,其类型为int*

该表达式&my_int返回一个指向my_int对象本身的指针,类型为std::unique_ptr<int>*

并且integers[0]是与 截然不同的对象my_int。它们恰好包含相同的指针。这对于唯一指针来说是不利的:它们将一起尝试释放相同的内存两次。你必须使用std::move

auto my_int = std::make_unique<int>(1);
std::vector<std::unique_ptr<int>> integers;
integers.emplace_back(std::move(my_int)); // push_back also works
Run Code Online (Sandbox Code Playgroud)

这种方式my_int将被设置为包含nullptr,并且只integers[0]包含指向分配内存的指针。


为了my_int更好地理解(或一般的指针),您可能会认为它是这样的:

+--------+ +---+
| my_int | --> | 1 |
+--------+ +---+
^ ^
| |
&my_int my_int.get()

integers[0].get()和是一样的&integers[0]