gpt4 book ai didi

c++ - 为什么 std::unique_ptr 构造函数接受外部指针?

转载 作者:行者123 更新时间:2023-12-03 06:51:32 26 4
gpt4 key购买 nike

我对 cpp 比较陌生,正在学习智能点。我想知道以下几点:
为什么要建一个 std::unique_ptrlvalue允许吗?
只允许构建 std::unique_ptr 不是更安全吗?用右值来避免邪恶的事情?

std::unique_ptr<int> createInt() {
int* a = new int(99);
std::unique_ptr<int> foo(a);
delete a;
return foo;
}
我意识到你必须疯了才能写出这样的东西,但我很高兴让编译器为此对你大喊大叫。所以我想知道,为什么 unique_ptr 的左值初始化是一件事?
编辑:
用户@aler egal 更优雅地表达了我的想法:

"In principle, you could have a constructor unique_ptr<int>(int*&& ptr) which assumes ownership of ptr and then sets it to null. That would prevent a use-after-free in this specific example (because you'd be forced to std::move(a) and because calling delete on a null pointer has no effect) but it would be a very strange anti-pattern."

最佳答案

这是 dangling pointer 的经典示例是!
与智能指针看起来不同,它们只是普通(原始)指针的包装器,可以自行管理内存并为您提供一些附加功能。
考虑以下示例:

int* someFunc() {
int* ptr;
int* ptr2 = ptr;
delete ptr;
return ptr2;
}
这就是你本质上在做的。
它们被制作成可以用来代替原始拥有指针 任何时候 ;意思是,它们也可以悬挂!因此,如果不允许左值初始化,那是您不能使用智能指针的一个用例,尽管我同意,这是您也不能使用的一种情况!
上面带有智能指针的代码正是您所尝试的。
现在,C++ 将逻辑留给您……完全。如果您想用脚射击自己,请继续,C++ 不会吠叫。 C++ 不检查内存使用情况和缓冲区溢出以及对已删除内存的访问。简单地说,这是 C++ 程序员的工作,如果他/她想用脚开枪,他/她可以自由地这样做!

此外,通常建议使用 std::make_ptr()在ctor上,因为前者启用了异常(exception)

关于c++ - 为什么 std::unique_ptr 构造函数接受外部指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63716204/

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