简体   繁体   中英

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?

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.

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,

It's fine but it can potentially be slow.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM