如何将unique_ptr的原始指针传递给接受unique_ptr的函数?
How to pass raw pointer of unique_ptr to a function that takes in unique_ptr?
#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 对于以后要使用它的人来说一点也不好玩;)
令人惊讶的是,它看起来异常安全。
相关文章:
- 为什么 std::unique 不调用 std::sort?
- CLANG 编译器 说:变量"PTR"可能未初始化
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 将 ptr 传递给 ptr 到 A 作为参数传递给 A 的函数是不好的做法吗?
- 为共享 ptr 向量实现复制 c'tor?
- 字符和整数中 **(ptr+1) 的值差异
- C++:在不中断共享的情况下通过引用传递共享 PTR?
- 生成"unique"矩阵
- 如何将派生类从基 ptr 分配给 nlohmann::json
- 引用 std::shared:ptr 以避免引用计数
- 我对 std::unique(算法)C++有问题
- 为什么我不能在不进行任何转换的情况下将浮点数放入任何类型的 ptr 中?
- 在调用函数时,ptr** 和 ptr*& 之间是否有区别,或者首选C++?
- 另一种类型的智能ptr,比如具有弱refs的unique_ptr
- 尝试打印出 *ptr++ 的值,以了解它是如何工作的
- 如何控制共享 ptr 引用计数?
- std::shared_ptr::unique(),复制和线程安全
- 如何在C++03中用自定义谓词调用std::unique
- C++中的指针否定 (!ptr == NULL)
- C++14 unique_ptr并使用已删除的函数'std::unique-ptr' unique_ptr错误