使用本地原始指针初始化 std::unique_ptr 时会发生什么?

What happens when a std::unique_ptr is initialized with a local raw pointer?

一段代码片段:

std::unique_ptr<SDL_Renderer, decltype(&SDL_DestroyRenderer)>
cGraphics::Create_Renderer()
{
    SDL_Renderer* temprenderer = SDL_CreateRenderer(m_Window.get(), -1, 0);
    SDL_SetRenderDrawColor(temprenderer, 255, 255, 255, 0xff);
    return std::unique_ptr<SDL_Renderer,
                           decltype(&SDL_DestroyRenderer)>(temprenderer,
                                                           SDL_DestroyRenderer);
}

我知道的:

我的问题:

为什么原始指针的销毁对临时唯一指针的副本没有影响,临时唯一指针本身(临时唯一指针)是用原始指针初始化的?换句话说,在保持信息不丢失的唯一指针内部发生了什么?

我的假设是唯一指针也包含一个原始指针(例如.get()),当它由temprenderer启动时,它会将temprenderer的值复制到原始指针上指针,并且当唯一指针超出范围时再次复制该信息。

好的,经过我的思考,现在听起来很明显,但如果有人能证实这一点,我将不胜感激。我还发现了这个:

A unique_ptr explicitly prevents copying of its contained pointer (as would happen with normal assignment)

所以当我们 return 一个 unique_ptr?

时,也许会发生一些额外的事情

当我们return临时unique_ptr时,编译器实际上"moves"通过调用移动构造函数来获取资源。一旦它移动了资源,原来的临时 unique_ptr 就会超出范围并被销毁。即使 unique_ptr 是一个左值,但如果编译器可以确定它在函数 returns 之后无论如何都会超出范围(不再需要),它会执行 copy elision 和 select returning.

的移动构造函数

Why does the destruction of the raw pointer have no effect on the copy of the temporary unique pointer, which itself (the temporary unique pointer) is initialized with the raw pointer? In other words, what happens inside of that unique pointer that keeps the information from being lost?

因为被销毁的不是内容而是保存地址的变量。一旦 unique_ptr 有了内容的地址,为什么它仍然很重要?

My assumption is that the unique pointer also holds a raw pointer (e.g. .get()), and when it is initiated by temprenderer it copies the value of temprenderer onto the raw pointer, and that information is again copied when the unique pointer goes out of scope.

当用temprenderer初始化unique_ptr时,它只是将temprenderer指向的地址复制到它自己的成员变量中。当控制超出范围时,该信息未复制移动(所有权转让)

您可能想看看如何 unique_ptr is returned from a function

A unique_ptr explicitly prevents copying of its contained pointer (as would happen with normal assignment)

template<class U, class E>
unique_ptr(unique_ptr<U, E>&& u) noexcept;

U 是 MoveConstructible 和 MoveAssignable,但是 不是 CopyConstructible 也不是 CopyAssignable 根据 unique.ptr/4.

因此,它可以防止复制。相反,它 转让 所有权。