一段代码片段:
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);
}
我所知道的:
temprenderer
在超出范围时当然会被销毁;- 一个临时的
std::unique_ptr
被原始指针初始化; - 虽然
std::unique_ptr
不允许复制,但是按值返回是可以的; - 本质上,临时
std::unique_ptr
在超出范围时也会被销毁; - 我们现在持有该临时唯一指针的拷贝
我的问题:
为什么原始指针的销毁对临时唯一指针的拷贝没有影响,临时唯一指针本身(临时唯一指针)是用原始指针初始化的?换句话说,在防止信息丢失的唯一指针内部发生了什么?
我的假设是,唯一指针也包含一个原始指针(例如 .get()
),当它由 temprenderer
启动时,它会复制 temprenderer
到原始指针上,当唯一指针超出范围时,该信息将再次复制。
好吧,经过我的思考,现在听起来很明显,但如果有人能证实这一点,我将不胜感激。我还发现了这个:
A unique_ptr explicitly prevents copying of its contained pointer (as would happen with normal assignment)
所以当我们返回一个 unique_ptr
时可能会发生一些额外的事情?
最佳答案
当我们返回一个临时的 unique_ptr
时,编译器实际上通过调用移动构造函数来“移动”资源。一旦它移动了资源,原始的临时 unique_ptr
就会超出范围并被销毁。即使 unique_ptr
是一个左值,但如果编译器发现它在函数返回后无论如何都会超出范围(不再需要),它会执行复制省略 并选择要返回的移动构造函数。
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.
当 unique_ptr
被 temprenderer
初始化时,它只是将 temprenderer
指向的地址复制到它自己的成员变量中。当控制超出范围时,该信息不会复制但会移动(所有权转让)。
关于c++ - 使用本地原始指针初始化 std::unique_ptr 时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50960134/