Re: Copy-less initialization of a TR1 array
On Nov 10, 12:30 pm, zr <zvir...@gmail.com> wrote:
Is there a way to initialize a std::tr1::array with a pre-allocated
built-in array in a copy-less assignment, such that both will point to
the same memory?
There is a way. Disclaimer: it is not blessed by the standard.
Vice-versa is easy to do, simply use std::t1::array::data() and assign
the returned value to the c-style pointer;
if STL does not support this, is there any other library that has such
a container (maybe BOOST)?
Here is an example of what i have in mind:
#include <array>
using namespace std::tr1;
int main()
{
int cArray[] = { 1 , 2, 3, 4};
array<int,4> tr1Array(cArray); // Using some imaginary c-tor. Don't
want to copy. Want to use preallocated memory
Here you do:
// make sure that the binary layouts of
// array<> and C-array are the same
typedef int static_assert[sizeof(array<int,4>) == sizeof(cArray) ?
1 : -1];
// now do the hack
array<int,4>& tr1Array = reinterpret_cast<array<int,4>&>(cArray);
tr1Array[0] = 42;
assert(tr1Array[0] == cArray[0] == 42); // Both point to same mem=
ory
tr1Array[100] = 42; //In debug builds, this should raise an exception
cArray[100] = 42; //Much harder to catch
return 0;
}
--
Max