gpt4 book ai didi

c++ - std::unique_ptr 构造函数行为

转载 作者:行者123 更新时间:2023-12-01 18:04:40 25 4
gpt4 key购买 nike

首先,我知道我们应该使用 std::make_unique() 而不是调用 std::unique_ptr 构造函数,我知道为什么。

但是我正在查看 std::unique_ptr 的文档来打发时间并加深我对它的了解,我发现了 following examples关于构造函数的用法:

// unique_ptr constructor example
#include <iostream>
#include <memory>

int main () {
std::default_delete<int> d;
std::unique_ptr<int> u1;
std::unique_ptr<int> u2 (nullptr);
std::unique_ptr<int> u3 (new int);
std::unique_ptr<int> u4 (new int, d);
std::unique_ptr<int> u5 (new int, std::default_delete<int>());
std::unique_ptr<int> u6 (std::move(u5));
std::unique_ptr<int> u7 (std::move(u6));
std::unique_ptr<int> u8 (std::auto_ptr<int>(new int));

std::cout << "u1: " << (u1?"not null":"null") << '\n';
std::cout << "u2: " << (u2?"not null":"null") << '\n';
std::cout << "u3: " << (u3?"not null":"null") << '\n';
std::cout << "u4: " << (u4?"not null":"null") << '\n';
std::cout << "u5: " << (u5?"not null":"null") << '\n';
std::cout << "u6: " << (u6?"not null":"null") << '\n';
std::cout << "u7: " << (u7?"not null":"null") << '\n';
std::cout << "u8: " << (u8?"not null":"null") << '\n';

return 0;
}

它生成(我通过执行代码验证了它)以下结果:

u1: null
u2: null
u3: not null
u4: not null
u5: null
u6: null
u7: not null
u8: not null

我很难理解的是:

  • 为什么 u4 有效,而 u5 无效 (nullptr)?
  • 为什么 u7 有效,但 u6 无效?

也许这些问题非常基本,但我完全没有捕获要点。

如果有人能解答我这些问题,我将不胜感激。

最佳答案

std::move 被命名为 move 是有原因的。当您从一个 std::unique_ptr move 到另一个时,您 move 的那个将变成 nullptr。不可能是任何其他方式,毕竟它是一个唯一 ptr,并且两个共享相同数据的unique_ptr 实例会违反这一点。 (而且两者超出范围都会调用删除器两次,然后一切就都松了。)

关于c++ - std::unique_ptr 构造函数行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58013672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com