Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ What are the differences between Microsoft's ComPtr and c++ unique_ptr, shared_ptr? [duplicate]

Tags:

c++

c++11

I'm seeing cases of these pointer classes mixed in together in these projects.

Sometimes they use std:unique_ptr, shared_ptr, and sometimes I see Microsoft::WRL::ComPtr.

Just wondering what the differences are and how do I know which to use?

like image 476
William Fleurant Avatar asked Mar 18 '26 11:03

William Fleurant


1 Answers

std::unique_ptr signifies a unique pointer to an object, such that you can not copy the pointer; but you may still move the pointer.

e.g.

auto ptr = std::make_unique<float>(5.0f);
std::unique_ptr other_ptr = ptr;

will not compile, but

auto ptr = std::make_unique<float>(5.0f);
std::unique_ptr other_ptr = std::move(ptr);

will.


std::shared_ptr signifies a pointer to an object that multiple other shared_ptrs may point to. It is copyable and movable.

The reason you would not use shared_ptr over unique_ptr all the time is that shared_ptr will be slower upon construction and deconstruction and any time you need to pass it into a function, you may incur this slow (de)construction.

as an example

auto ptr = std::make_shared<float>(5.0f);
std::shared_ptr other_ptr = ptr;

is (maybe a lot) slower than moving the original pointer into the new one because the compiler has to keep track of how many shared_ptr instances point to the object so that when a shared_ptr is de-constructed if it is the last pointer to that object it will delete it.


As for ComPtr... please don't use it unless absolutely necessary. Which is almost never. The reason why you probably see it used within the project you refer to is that some Microsoft specific APIs use it, which is one of those times where you do have to use it.


EDIT

To show the advantages and/or disadvantages of these different smart pointers, and when you should be choosing them, a decent example program is really necessary. So here you go!

void f(std::unique_ptr<float> p){}
void f(std::shared_ptr<float> p){}

void g(std::unique_ptr<float> &p){}
void g(std::shared_ptr<float> &p){}

int main(int argc, char *argv[]){
    auto uptr = std::make_unique<float>(6.9f);
    auto sptr = std::make_shared<float>(4.20f);

    // f(uptr);
    // error, trying to make a copy of a unique_ptr

    f(sptr);
    // fine, shared_ptr may be copied

    f(std::make_unique<float>(6.9f));
    f(std::make_shared<float>(4.20f));
    // both fine, value initialized in function call and moved into function.

    g(uptr);
    g(sptr);
    // both fine, shared and unique pointers may be passed by reference
    // as no copy or move is made.
}
like image 109
RamblingMad Avatar answered Mar 20 '26 01:03

RamblingMad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!