gpt4 book ai didi

c++ - 如何将原始指针包装到 shared_ptr 中并防止 shared_ptr 删除对象?

转载 作者:搜寻专家 更新时间:2023-10-31 01:10:51 27 4
gpt4 key购买 nike

我需要将原始指针包装到 shared_ptr 中,以便将其传递给函数。该函数在返回后不保留对输入对象的任何引用。

{
MyClass i;
shared_ptr<MyClass> p(&i);
f(p);
// BAD: shared_ptr will delete i.
}

如何防止shared_ptr删除引用的对象?

最佳答案

作为chris在评论中提到,写一个空的删除器:

#include <type_traits>

template <typename T>
struct empty_delete
{
empty_delete() /* noexcept */
{
}

template <typename U>
empty_delete(const empty_delete<U>&,
typename std::enable_if<
std::is_convertible<U*, T*>::value
>::type* = nullptr) /* noexcept */
{
}

void operator()(T* const) const /* noexcept */
{
// do nothing
}
};

使用示例:

#include <iostream>
#include <memory>

struct noisy
{
noisy() { std::cout << "alive" << std::endl; }
~noisy() { std::cout << "dead" << std::endl; }

noisy(const noisy&);
noisy& operator=(const noisy&);
};

template <typename T>
void take(T& yours)
{
std::cout << "Taking..." << std::endl;
{
auto mine = std::move(yours);
}
std::cout << "Took." << std::endl;
}

int main()
{
std::unique_ptr<noisy> a(new noisy());
std::shared_ptr<noisy> b(new noisy());
std::unique_ptr<noisy, empty_delete<noisy>> c(new noisy());
std::shared_ptr<noisy> d(new noisy(), empty_delete<noisy>());

take(a);
take(b);
take(c);
take(d);
}

输出:

alive
alive
alive
alive
Taking...
dead
Took.
Taking...
dead
Took.
Taking...
Took.
Taking...
Took.

当然,这个例子会泄漏内存。

关于c++ - 如何将原始指针包装到 shared_ptr 中并防止 shared_ptr 删除对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15534146/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com