C++ Logo

sg12

Advanced search

Re: [ub] Type punning to avoid copying

From: Ion Gaztañaga <igaztanaga_at_[hidden]>
Date: Fri, 26 Jul 2013 20:33:27 +0200
El 26/07/2013 18:10, Gabriel Dos Reis escribió:
> Jeffrey Yasskin <jyasskin_at_[hidden]> writes:
>
> | On Fri, Jul 26, 2013 at 8:30 AM, Gabriel Dos Reis <gdr_at_[hidden]> wrote:
> | > Ion Gaztañaga <igaztanaga_at_[hidden]> writes:
> | >
> | > [...]
> | >
> | > | ¿How can we tell the compiler that a memory buffer is really a different
> | > | type?
> | >
> | > Invoke a constructor to turn the raw memory into an object of the
> | > desired type.
> |
> | Can you point to the wording that explains the behavior in that case?
>
> I am not sure I understand your request. Ion wants to state a region of
> storage is of a given type. The behavior after the contructor ran is
> what you get after running a constructor -- see section 12.1.

We don't want to run the constructor because the constructor might touch
bytes that are already set by an external source, we want to tell the
compiler that the object is already correctly constructed. Most C++
programmers expect this feature to be available in the language, because
they have been using it for decades:

Example 1:

void *p = mmap(/**/);

//Mr. Compiler, believe me, a properly constructed
//object of type Class lives in address p
//(constructed by another process compiled with a
//compatible ABI)
Class *pt = reinterpret_cast<Class *>(p);

Example 2:

vector<char> network_packet(EthernetLength);

if(eth_controller_read(network_packet.data(), network_packet.size())){
    //Mr. Compiler, believe me, a properly constructed
    //object of type PacketUnion lives in address network_packet.data().
    PacketUnion *pt =
      reinterpret_cast<PacketUnion *>(network_packet.data());
}

Example 3:

//Mr. Compiler, believe me, a properly constructed
//object of type DeviceStatusStruct lives in address 0x12345678.
volatile DeviceStatusStruct *pd =
   reinterpret_cast<volatile DeviceCtrlStruct*>(0x12345678);

----
And to complicate things a little bit, we would like a solution that is 
compatible with C, and C has no constructors. How can we solve this?
Best,
Ion

Received on 2013-07-26 20:33:51