Storing std/boost::arrays in a vector

Apr 10, 2017 at 2:45am
Since I assume this wont make a deep copy of the array (but instead just copy the pointer) I was wondering what is the proper way to store a copy of std or boost array.

1
2
3
4
void AddAnother(array<uint32_t,4> &temporaryArray)
{
	myVector.push_back(temporaryArray);
}
Apr 10, 2017 at 3:15am
> I assume this wont make a deep copy of the array (but instead just copy the pointer)

std::array<> has value semantics, a copy of the array would be made.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <array>

int main()
{
    const std::array<int,25> a {} ;
    auto cpy = a ;

    std::cout << std::boolalpha << (a==cpy) << '\n' // true
              << ( a.begin() == cpy.begin() ) << '\n' ; // false

    cpy[4] = 78 ; // the copy is modified
    std::cout << (a==cpy) << '\n' ; // false
}
Apr 10, 2017 at 3:15am
The data() member method of std::array
(r)eturns pointer to the underlying array serving as element storage

http://en.cppreference.com/w/cpp/container/array/data
so, for example:
1
2
3
4
5
6
std::vector<uint32_t*> AddAnother(std::array<uint32_t,4> &temporaryArray)
{
	std::vector<uint32_t*> myVec{};
	myVec.push_back(temporaryArray.data());
	return myVec;
}
Apr 10, 2017 at 4:57am
@JLBorges Great so the a duplicate would be stored in the vector. Looks like I assumed wrong. Thanks!


@gunnerfunner I think you misunderstood my problem, the temporary array will be destroyed right after calling this function. So there is no point in storing the data pointer.
Topic archived. No new replies allowed.