Question

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 );
}
Was it helpful?

Solution

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] )

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top