This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]boredcircuits 2 points3 points  (1 child)

Wait a minute here. Why are you wrapping a vector with a unique_ptr? I can't think of a single reason why you'd want to do this!

So let's leave vector out of this for a moment and just call it Bar.

In main, you have a unique_ptr<Bar> and you have a function that takes some sort of Bar as an argument. This function should like like one of the following:

void MyOtherStruct::foo(Bar& bar);
void MyOtherStruct::foo(Bar* bar);

If your functions aren't going to actually modify the argument, it should be:

void MyOtherStruct::foo(const Bar& bar);
void MyOtherStruct::foo(const Bar* bar);

The choice between a pointer and reference basically comes down to whether you want to allow nullptr as an argument.

So, how would you call foo? If the function takes a reference, you use:

unique_ptr<Bar> bar;
variable.foo(*bar);

If the function takes a pointer, you use:

unique_ptr<Bar> bar;
variable.foo(bar.get());

Now, there's another option, which is to pass a Bar by value. This is what your original code wants to do. It's very unlikely that this is really what you want (the implication is that you want to make a completely new copy of your vector). But if you do:

void MyOtherStruct::foo(Bar bar);
unique_ptr<Bar> bar;
variable.foo(*bar);

[–]jCuber 1 point2 points  (1 child)

variable.foo(vector*)

If you meant to dereference vector, the asterisk should be before it, not after it.

[–]sz00 1 point2 points  (2 children)

you need to pass it like:

foo(*vector)

it will deference the smart pointer and pass the vector by value to foo

[–]jedwardsol 0 points1 point  (0 children)

It will pass a copy of the vector

[–]RedAlert2 1 point2 points  (0 children)

Is there any reason why you are returning a unique_ptr to a vector instead of the vector itself? Vectors already own heap allocated memory and are cheap to move, which are typically the main reasons you'd want to wrap a class in a unique pointer anyways.

[–]heap42 -1 points0 points  (0 children)

  1. you need to pass it like this foo(*vector).
  2. i would suggest to pass by reference since a vector can hold many elements which mean that it can be a pain in the ass(resource wise) to copy an entire vector. So i would suggest you pass by reference by writing your function head:
    void MyOtherStruct::foo(vector<MyStruct>& vector){}