C++ 如何在不同的范围内重新分配unique_ptr?

C++ 如何在不同的范围内重新分配unique_ptr?,c++,unique-ptr,C++,Unique Ptr,我尝试了以下方法: #include <iostream> #include <memory> using namespace std; class Obj { public: Obj(int x) : x(x) {} int x; }; void func(unique_ptr<Obj> o) { o = make_unique<Obj>(new Obj(5)); } int main()

我尝试了以下方法:

#include <iostream>
#include <memory>

using namespace std;

class Obj {
    public:
        Obj(int x) : x(x) {}
        int x;
};

void func(unique_ptr<Obj> o) {
    o = make_unique<Obj>(new Obj(5));
}

int main()
{
    unique_ptr<Obj> o;
    func(o);
    cout << o->x << endl;
    return 0;
}
但它的回报是:

main.cpp: In function ‘void func(std::unique_ptr<Obj>)’:
main.cpp:21:9: error: ‘make_unique’ was not declared in this scope
     o = make_unique<Obj>(new Obj(5));
         ^~~~~~~~~~~
main.cpp:21:24: error: expected primary-expression before ‘>’ token
     o = make_unique<Obj>(new Obj(5));
                        ^
main.cpp: In function ‘int main()’:
main.cpp:27:11: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Obj; _Dp = std::default_delete]’
     func(o);
如何在函数中重新分配指针

编辑:

我还尝试:

void func(unique_ptr<Obj> o) {
    o.reset(new Obj(5));
}
将返回此错误:

main.cpp: In function ‘int main()’:
main.cpp:27:11: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Obj; _Dp = std::default_delete]’
     func(o);
           ^

您需要使用一个可变的引用参数,以及一个in/out或update参数

#include <iostream>
#include <memory>

using namespace std;

class Obj {
public:
    Obj(int x) : x(x) {}
    int x;
};

void func(unique_ptr<Obj>& o) {
    o = make_unique<Obj>(5);
}

int main() {
    unique_ptr<Obj> o;
    func(o);
    cout << o->x << endl;
    return 0;
}

您需要使用一个可变的引用参数,以及一个in/out或update参数

#include <iostream>
#include <memory>

using namespace std;

class Obj {
public:
    Obj(int x) : x(x) {}
    int x;
};

void func(unique_ptr<Obj>& o) {
    o = make_unique<Obj>(5);
}

int main() {
    unique_ptr<Obj> o;
    func(o);
    cout << o->x << endl;
    return 0;
}

1.你没有包括2个。func只有在编译时才会重新分配其本地指针。3.你的main有多个问题,包括试图将一个Obj转换成一个std::unique\u ptr,但它不起作用。我编辑了我的帖子,很匆忙,对不起。你不能复制std::unique\u ptr,所以你的函数没有什么意义。也许您想通过引用获取std::unique\u ptr?void funcunique\u ptr&o{o.resetnew Obj5;},因为您需要通过引用传递参数,而不是通过值为unique\u ptr删除复制构造函数。无论如何,你的设计是完全错误的。如果确实需要重置,请直接从函数返回指针,然后使用它。不要将智能指针作为参数传递。U'v遇到多个问题。缺少引用语法、右值引用/移动语义、唯一\u ptr语义。。。正确的答案应该很长。你没有包括2个。func只有在编译时才会重新分配其本地指针。3.你的main有多个问题,包括试图将一个Obj转换成一个std::unique\u ptr,但它不起作用。我编辑了我的帖子,很匆忙,对不起。你不能复制std::unique\u ptr,所以你的函数没有什么意义。也许您想通过引用获取std::unique\u ptr?void funcunique\u ptr&o{o.resetnew Obj5;},因为您需要通过引用传递参数,而不是通过值为unique\u ptr删除复制构造函数。无论如何,你的设计是完全错误的。如果确实需要重置,请直接从函数返回指针,然后使用它。不要将智能指针作为参数传递。U'v遇到多个问题。缺少引用语法、右值引用/移动语义、唯一\u ptr语义。。。正确的答案应该很长。