简体   繁体   中英

Getting rid of the inefficiency of redundant dereference

Problem

I have an object with unique_ptr as a field:

class SomeObject
{
    std::unique_ptr<int> someUnique;
public:
    // ...
};

When I want to pass the object to a function without passing its ownership, I have to pass it by reference. Thus I have two dereferences instead of one. Since I have some virtual functions, it can't always be optimized away. How can I get rid of this inefficiency?

Example here .

Solution

I don't like this solution, although it's working.

I can seperate the ownership from the classes - from all (except some dedicated structs, for ownership only, and without any methods or private fields) of the classes. Thus, no class will ever contain things like unique_ptr, but only raw pointers. Because sometimes (most of the times, actually) it makes sense to couple the lifetime of an object to some resource, I will have the next struct:

template<typename THeld, typename THolder>
struct Unit
{
    THeld held;
    THolder holder;
};

When holder a is unique_ptr or tuple of unique_ptrs or something, and held is an object that can be copied freely and has only raw pointers, if any.

But this solution is really code bloating, because now each (or at least, a lot of) class should have static Make(...) function, which returns a Unit and allocates the appropriate resources. (Unfortonately, it took me time to understand that it such a code bloat)

Is there a better solution?

PS Yes, performace are really crucial.

Add a member function .get() to SomeObject which returns a SomeNotOwnedObject which holds a pointer obtained from someUnique.get() and pass that by-value to functions.

This basically wraps the usual convention of passing non-owning pointers as raw pointers, and std::unique_ptr::get() in case of pointers owned by a std::unique_ptr .

SomeNotOwnedObject is then a "fancy pointer" extending the behavior of a native pointer and SomeObject is the std::unique_ptr equivalent supporting the "fancy" interface of SomeNotOwnedObject .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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