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

How to reassign unique_ptr in a different scope?

我尝试了以下方法:

#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;
}

但是 returns:

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));
}

其中returns这个错误:

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”或“更新”参数。

#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;
}

但您还考虑做的是:

  • 避免using namespace std;
  • 避免in/out参数;更喜欢 return 值
  • 避免隐藏变量
  • 启用您可以容忍的所有编译器警告;修复导致警告的代码
  • const 正确性

clang++ -Weverything -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-padded -Wno-c99-compat -pedantic -fsanitize=undefined,null -std=c++17 -cxx-isystem /usr/local/include a.cpp -o a.out

#include <iostream>
#include <memory>

using std::cout;
using std::make_unique;
using std::unique_ptr;

namespace {

class Obj {
    int _x;
public:
    Obj(int x) : _x{x} {}
    int x() const { return _x; }
};

unique_ptr<Obj> func() {
    return make_unique<Obj>(5);
}

} // anon

int main() {
    auto o = func();
    cout << o->x() << "\n";
}