Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass a vector of unique_ptr s to a function

Tags:

c++

How do I pass a vector of unique_ptr to a function to access each individual objects functions and variables? The pointers point to the derived class through base class object. The derived classes are for example, triangle, plane, sphere etc.

So far, I've been try to do this:

void foo(vector<unique_ptr<object>>& shapes)
{
    // do something
}

But the problem with this is that unique_ptr can't be copied. I don't know if creating a reference would work, but I assume I have to use the move function. That or I'm not sure if shared_ptr is a good idea. The objects are dynamically allocated.

like image 612
JerSci Avatar asked Oct 23 '25 15:10

JerSci


1 Answers

How to pass a vector of unique_ptr to a function to access each individual objects fucntions and variables

Do it as you have shown in the question. It works just fine.

the problem with this is that unique_ptr can't be copied

That is not a problem, because the unique_ptrs are not being copied.

I'm not sure if shared_ptr are a good idea.

No, they are not good idea unless you really need shared ownership.

like image 97
Acorn Avatar answered Oct 26 '25 04:10

Acorn



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!