kfmfe04
kfmfe04

Reputation: 15327

What is the right way to pass an array of unique_ptrs?

Is this the right way to pass an array of unique_ptrs if I want no copies?

In other words, I want everything that happens to x to impact arr in the caller.

void doWork( unique_ptr<Foo> x[] )
{
    // I want assignments to x to impact caller's arr
}

int main()
{
    unique_ptr<Foo> arr[10];
    doWork( arr );
}

Upvotes: 2

Views: 1140

Answers (3)

Chris Dodd
Chris Dodd

Reputation: 126243

You pass a pointer instead. Since you can't pass arrays to functions anyways, you code already does that -- the compiler will silently and confusingly turn any function parameters declared as arrays into pointers.

Upvotes: 0

CB Bailey
CB Bailey

Reputation: 791979

What you're doing is fine for what you want (although I'm not sure it's the best design).

Because arrays decay to pointers when passed to functions and functions declared as taking arrays are adjusted to functions taking pointers, inside doWork, x is a pointer to the array of unique_ptr<Foo> arr declared in main and assignments to the members of the array will be visible in main.

Upvotes: 0

sehe
sehe

Reputation: 393114

Your code has no real problem, because arrays decay to pointers1 when passed like this (by value). However, the following sure would be more C++:

typedef std::vector<std::unique_ptr<Foo> > FooVec;   // dynamic size
typedef std::array<std::unique_ptr<Foo>, 10> FooArr; // fixed size (10)

void doWork( FooVec& x ) // or FooArr&
{
    // I want assignments to x to impact caller's arr
}

int main()
{
    FooVec vec(10); 
    FooArr arr;
    doWork( vec );
}

1 In other words, it is equivalent to

void doWork( unique_ptr<Foo> *x )

To stop decay, pass by reference:

void doWork( unique_ptr<Foo> (&x)[10] )

Upvotes: 10

Related Questions