samedi 23 octobre 2021

picewise_construct constructing multiple objects

I'm experimenting a bit with piecewise_construct. Consider this code:

#include <iostream>
#include <utility>
#include <tuple>

using namespace std;

struct Foo
{
    Foo( tuple<int, int, int> &tpl )
    {
        cout << "... from a tuple\n";
        cout << "this: " << (void *)this << ", &tpl: " << (void *)&tpl << endl;
        cout << "i: " << std::get<0>( tpl ) << endl;
        cout << "j: " << std::get<0>( tpl ) << endl;
        cout << "k: " << std::get<2>( tpl ) << endl;
    }
    Foo( int i, int j, int k )
    {
        cout << "... from three ints\n";
        cout << "this: " << (void *)this << endl;
        cout << "i: " << i << endl;
        cout << "j: " << j << endl;
        cout << "k: " << k << endl;
    }
};

int main()
{
    tuple<int, int, int> tplA( 1, 2, 3 ), tplB( 4, 5, 6 );
    pair<Foo, Foo> pffA( tplA, tplB );
    cout << (void *)&pffA << endl;
    pair<Foo, Foo> pffB( piecewise_construct, tplA, tplB );
    cout << (void *)&pffB << endl;
    return -1;
}

The output is on my computer for a 32 bit process:

... from a tuple
this: 00A0FC4C, &tpl: 00A0FC6C
i: 1
j: 1
k: 3
... from a tuple
this: 00A0FC4D, &tpl: 00A0FC58
i: 4
j: 4
k: 6
00A0FC4C
... from three ints
this: 00A0FC40
i: 1
j: 2
k: 3
... from three ints
this: 00A0FC41
i: 4
j: 5
k: 6
00A0FC40

I'asking myself whether I there are two objects created from pffA and pffB although I can access only the one created first (00A0FC4C / 00A0FC40). That's feature which doesn't make sense to me. What it is good for ?

Aucun commentaire:

Enregistrer un commentaire