简体   繁体   English

在c ++中将指针解引用到引用中

[英]Dereferencing a pointer into a reference in c++

In the following code snippet, are there any caveats that need to be considered? 在以下代码段中,是否有任何需要考虑的警告?

void do_stuff()
{
    std::unique_ptr<my_type> my(new my());

    my_type& mine = *my;

    //use mine 
}

It gives me a weird feeling to 'bring out' the value of my by dereferencing the implicit pointer, as it feels like it would create a temporary (but I'm quite sure that's not the case) 通过解除引用隐式指针来“带出”我的价值给我一种奇怪的感觉,因为它感觉它会创建一个临时的(但我很确定不是这样)

The code is fine with the usual caveats when holding a reference (or pointer) to an object: you have to make sure that the object outlives the uses of the pointer or reference. 当持有对象的引用(或指针)时,代码很好用通常的警告:你必须确保对象比指针或引用的使用寿命更长。

In this particular case, make sure that the object inside the unique_ptr does not get deleted by a call to reset() or delete my.release(); 在这种特殊情况下,请确保通过调用reset()delete my.release();来删除unique_ptr中的对象delete my.release(); which I think are the only cases where the lifetime of that reference might outlive the lifetime of the object itself. 我认为这是唯一的情况,该引用的生命周期可能比对象本身的寿命更长。

Side note: I am assuming that you have a good reason to use dynamic allocation for that object. 旁注:我假设您有充分的理由为该对象使用动态分配。 If you are not sure, consider not using pointers/new in the first place. 如果您不确定,请考虑不首先使用指针/ new。

I am also assuming that the reference is not there for performance , if it is, you might want to consider as access through the reference or the smart pointer will be translated to exactly the same binary. 我也假设引用不是为了性能 ,如果是,你可能想要通过引用考虑访问,或者智能指针将被转换为完全相同的二进制文件。

除了没有多大意义(至少在代码片段中)代码是正常的,如果在构造my和引用的赋值之间确实没有任何内容。

Make sure that the pointer outlives the (use of the) reference. 确保指针超过(使用)引用。

One simple way to do that is to use const : 一种简单的方法是使用const

void doStuff()
{
    auto const p    = std::unique_ptr<MyType>( new MyType );
    MyType&    m    = *p;

    // use m
}

Of course, if there is not any special reason to prefer dynamic allocation (such as size, or special allocator) then just use automatic allocation for the MyType object, ie declare it directly as a local variable without using the word static . 当然,如果没有任何特殊原因需要动态分配(例如大小或特殊分配器),那么只需对MyType对象使用自动分配 ,即直接将其声明为局部变量而不使用static

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM