How to avoid big memory allocation with std::make_shared

后端 未结 3 1429
遥遥无期
遥遥无期 2020-12-16 16:26

Let\'s say that I have some arbitrary class, A:

class A {
 //... stuff
};

I want to call into an external API that takes in a shared pointe

相关标签:
3条回答
  • 2020-12-16 17:14

    If you know that shared pointer you pass to foo() will not get stored, copied etc, ie will not outlive your object you can make std::shared_ptr pointed to object on the stack with empty deleter:

    void emptyDeleter( A * ) {}
    
    A a;
    foo( std::shared_ptr<A>( &a, emptyDeleter ) );
    

    Again you need to make sure that shared pointer or it's copy will not outlive the object and well document this hack.

    0 讨论(0)
  • 2020-12-16 17:17

    This is possible with the shared_ptr constructor that allows for an "empty instance with non-null stored pointer":

    A x;
    std::shared_ptr<A> i_dont_own(std::shared_ptr<A>(), &x);
    

    (It's "overload (8)" on the cppreference documentation.)

    0 讨论(0)
  • 2020-12-16 17:22

    Assuming class A supports move semantics, do this:

    std::shared_ptr<A> newA = make_shared<A> (std::move (_a));
    

    Do not use _a anymore, use only newA. You can now pass newA to the function.

    If class A does not support move semantics, there is no safe/sane way to do this. Any hack will only happen to work, and may break in the future. If you control enough of the class code, you may be able to add support for move semantics.

    But from what I can tell, a new instance of A is still created.

    Why do you care? What you're trying to avoid is copying all the data in the instance, and this does that.

    The point of move semantics is to move the data from one instance to another without having to do an allocate/copy/free. Of course, this makes the original instance "empty", so don't use that anymore.

    0 讨论(0)
提交回复
热议问题