asimes
asimes

Reputation: 6080

Is std::array safely returnable

Is the below sample function safe from the caller's point of view?

std::array<T, SIZE> foo() {
    std::array<T, SIZE> bar;
    // Initialization of bar members...
    return bar;
}

I am aware that built-in arrays are not safely returnable but I am unsure if std::array is safely returnable. If it is, how is this accomplished?

Upvotes: 1

Views: 413

Answers (3)

frogatto
frogatto

Reputation: 29285

As @Brian mentioned std::array is a struct that has an array member. Something like this:

template<typename T, std::size_t N>
struct my_array {
    T array[N];
};

Note that when you copy a my_array, its array is deeply copied. So returning such structs from a function, which makes a copy to a temporary object, would never cause problems. So, with or without presence of RVO, it always ensures that there will be no problem.

my_array<int, 5> foo = {1, 2, 3, 4, 5};
my_array<int, 5> bar;

// Copy assignment here
bar = foo;

// Change bar's first element
bar.array[0] = 12;

// Print foo
std::copy(std::begin(foo.array),
          std::end(foo.array),
          std::ostream_iterator<int>(std::cout, ", "));

Result:

1, 2, 3, 4, 5,

Upvotes: 1

cshu
cshu

Reputation: 5954

It's fine but it can potentially be slow.

C++17 introduces guaranteed copy elision, but NRVO is not included.

Upvotes: 0

Brian Bi
Brian Bi

Reputation: 119467

This is fine. Returning bar from foo() makes a copy.

std::array is a struct that has an array member. When such a struct is copied, the array is also copied. In other words, the rules differ for bare arrays and arrays contained in structs.

Upvotes: 4

Related Questions