Re: Copy-less initialization of a TR1 array

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • zr

    Re: Copy-less initialization of a TR1 array

    On Nov 10, 6:35 pm, Maxim Yegorushkin <maxim.yegorush ...@gmail.com>
    wrote:
    On Nov 10, 4:20 pm, Vidar Hasfjord <vattilah-gro...@yahoo.co .uk>
    wrote:
    >
    On Nov 10, 12:30 pm, zr <zvir...@gmail. comwrote:
    >
    Hi,
    >
    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?
    >
    Yes, you can use 'placement new':
    >
        typedef array <int, 4A;
        int init [] = {1, 2, 3, 4};
        A& a = *new (init) A;
    >
    A may overflow init.
    >
    Of course, this is equivalent to
    >
        array <int, 4a = {1, 2, 3, 4};
    >
    Only with POD types. If you replace int with a non-trivial type, this
    code will end up calling constructors twice and destructors only once.
    >
    --
    Max
    I had to write a small test to realize the problem, though i don't
    understand what is really happening.
    Max, or anyone could you please elaborate?

    #include <array>
    #include <iostream>

    using namespace std::tr1;
    using namespace std;

    class A
    {
    public:
    A():value(10) { cout << "A() c-tor\n"; }
    A(const int& _value):value(_ value) { cout << "A(const int& _a) c-tor
    \n"; }
    ~A() { cout << "A d-tor\n"; }
    int value;
    };

    int main(int argc, char* argv[])
    {
    A cArray[] = { 1 , 2, 3, 4};

    array<A,4>& tr1Array = *new(cArray) array<A,4>;

    for (int i=0; i<4; i++)
    cout << cArray[i].value << " ";
    cout << endl;
    for (int i=0; i<4; i++)
    cout << tr1Array[i].value << " ";
    cout << endl;

    return 0;
    }

    output:
    A(const int& _a) c-tor
    A(const int& _a) c-tor
    A(const int& _a) c-tor
    A(const int& _a) c-tor
    A() c-tor
    A() c-tor
    A() c-tor
    A() c-tor
    10 10 10 10
    10 10 10 10
    A d-tor
    A d-tor
    A d-tor
    A d-tor
Working...