使用引用更新智能指针 [英] Update a smart pointer using a reference

查看:188
本文介绍了使用引用更新智能指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从引用更新智能指针。

I would like to update a smart pointer from a reference.

shared_ptr<My_Toy> my_toy_ptr;

// Something...

void update(shared_ptr<My_Toy> my_toy_ptr, My_Toy& toy){

     my_toy_ptr = &toy;
}

...但他的代码会产生错误。

...but his code generates an error.

我如何做这个操作?

推荐答案

分配对象到 std :: shared_ptr toy 将在其范围结束时被销毁, std :: shared_ptr 将尝试删除不是的东西。 std :: shared_ptr 必须是动态分配的对象的地址(虽然可以提供自定义删除器,但不是

Don't pass the address of a stack allocated object to a std::shared_ptr. toy will be destructed at the end of its scope and the std::shared_ptr will attempt to delete something that was not newd. The address held by a std::shared_ptr must be that of a dynamically allocated object (although a custom deleter can be provided, but that is not the case here).

要更改 std :: shared_ptr 正在管理的对象,请使用 std :: shared_ptr :: reset()

To change the object that a std::shared_ptr is managing use std::shared_ptr::reset().

这篇关于使用引用更新智能指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆