如何将现有对象的地址分配给智能指针? [英] How to assign the address of an existing object to a smart pointer?

查看:273
本文介绍了如何将现有对象的地址分配给智能指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <memory>

class bar{};

void foo(bar &object){
    std::unique_ptr<bar> pointer = &object;
}

我想将对象的地址分配给指针。上面的代码显然不会编译,因为赋值运算符的右侧需要是std :: unique_ptr。我已经尝试过:

I want to assign an address of the object to the pointer. The above code obviously wont compile, because the right side of the assignment operator needs to be a std::unique_ptr. I've already tried this:

pointer = std::make_unique<bar>(object)

但是在编译过程中会引发很多错误。我该怎么做?

But it throws many errors during compilation. How can I do that?

更新

如答案中所述-使用 std :: unique_ptr :: reset 方法导致未定义的行为。现在我知道,在这种情况下,我应该使用标准指针。

Update
As said in the answers - using the std::unique_ptr::reset method led to undefined behaviour. Now I know, that in such cases I should use a standard pointer.

推荐答案

尝试 std :: unique_ptr :: reset

void foo(bar &object){
    std::unique_ptr<bar> pointer;
    pointer.reset(&object);
}

但是请注意,不建议这样做,您不应为要传递给函数的引用创建 unique_ptr 。在该函数的末尾,当销毁 pointer 时,它也会尝试销毁 object 并赢得胜利在函数调用之外不可用,从而导致访问内存错误。

But be aware this is not recommended, you should not create a unique_ptr to a reference that is being passed to a function. At the end of the function, when pointer is being destroyed it will try to destroy object as well, and it won't be available outside the function call, resulting in an access memory error.

示例:这将编译,但会给出运行时错误。

Example: This will compile, but give a runtime error.

struct bar{ int num;};

void foo(bar &object){
    std::unique_ptr<bar> pointer;
    pointer.reset(&object);
}

int main()
{
    bar obj;
    foo(obj);
    obj.num; // obj is not a valid reference any more.
    return 0;
}

另一方面,您可能要考虑使用 shared_ptr 这可以帮助您确定: unique_ptr或shared_ptr之间的差异?

On the other hand you might want to consider using shared_ptr this can help you to decide: unique_ptr or shared_ptr?.

这篇关于如何将现有对象的地址分配给智能指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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