将Object转换为std :: unique_ptr

Pro*_*123 6 c++ pointers type-conversion

我有一个简单的菜鸟问题,我无法找到答案:

在C++中,如何转换常规对象

int i;
Run Code Online (Sandbox Code Playgroud)

变成了std::unique_ptr

std::unique_ptr<int> iptr = &i; //invalid
std::unique_ptr<int> iptr = static_cast<std::unique_ptr<int>>(&i); //invalid
Run Code Online (Sandbox Code Playgroud)

谢谢.

Pup*_*ppy 11

你没有.该对象不能被删除delete,这就是要做的unique_ptr事情.你需要

auto iptr = make_unique<int>();
Run Code Online (Sandbox Code Playgroud)

在这里,我们将make_unique定义为与make_shared相同的实用函数,它应该是标准的,但不幸的是被忽略了.这是简要的实施:

template<typename T, typename... Args> std::unique_ptr<T> make_unique(Args&&... args) {
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
Run Code Online (Sandbox Code Playgroud)


Jos*_*eld 5

你没有.i没有动态分配,因此不需要删除它.如果你在它的地址周围包裹了一个智能指针,它会delete &i在某个时刻执行并给你未定义的行为.你应该只new在智能指针中包装你所拥有的东西,如下所示:

std::unique_ptr<int> ptr(new int(5));
Run Code Online (Sandbox Code Playgroud)

智能指针的重点在于它为您管理动态分配对象的生命周期.i具有自动存储持续时间,因此将在其范围的最后被销毁.你不需要任何东西来帮助你.