如何将unique_ptr的原始指针传递给接受unique_ptr的函数?

How to pass raw pointer of unique_ptr to a function that takes in unique_ptr?

本文关键字:ptr unique 函数 原始 指针      更新时间:2024-09-30
#include <iomanip>
#include <iostream>
#include <memory>
#include <string>
#include <type_traits>
#include <utility>
class Res {
std::string s;
public:
Res(std::string arg) : s{ std::move(arg) } {
std::cout << "Res::Res(" << s << ");n";
}
~Res() {
std::cout << "Res::~Res();n";
}
private:
friend std::ostream& operator<< (std::ostream& os, Res const& r) {
return os << "Res { s = " << r.s << "; }";
}
};
// ptr is used just to read the content of the ptr.
// No writing is done. fun2 calls another api 
// lets say api_fun that requires unique_ptr
void fun2(std::unique_ptr<Res>& uniq_ptr){
// api_fun(uniq_ptr);
std::cout << uniq_ptr.get() << 'n';
}
void fun1(Res* ptr){
//std::unique_ptr<Res> tt(ptr);
//fun2(std::move(tt));// this deletes the mem twice.
}
int main()
{
std::unique_ptr<Res> up(new Res("Hello, world!"));
fun1(up.get());
// up will be used here too
}

我正在做一个具有unique_ptr变量的项目,比如说up.这unique_ptrup作为原始指针传递给fun1函数。现在在fun1里面我必须调用函数fun2但这需要unique_ptr。

正如fun2的评论中提到的.此函数仅读取指针的内容,不进行任何修改。

如何从原始指针将unique_ptr传递给fun2

Ps:有没有不修改 api 定义的解决方案?

编辑:fun2可以采取std::unique_ptr&

而不是使用get() 传递地址,您必须使用 release() 释放所有权

void api_fun(std::unique_ptr<Res> const&);
void fun2(std::unique_ptr<Res>& uniq_ptr){
api_fun(uniq_ptr);
std::cout << uniq_ptr.get() << 'n';
}
void fun1(Res* ptr){
std::unique_ptr<Res> tt(ptr);
fun2(tt);
tt.release();
}
int main()
{
std::unique_ptr<Res> up(new Res("Hello, world!"));
auto p = up.release();
fun1(p);
up.reset(p);
std::cout << "All good" << std::endl;
}

但是这些 fun1 和 fun2 对于以后要使用它的人来说一点也不好玩;)

令人惊讶的是,它看起来异常安全。