Strict anti-aliasing rule

I read notes about reinterpret_cast and aliasing rules ( http://en.cppreference.com/w/cpp/language/reinterpret_cast ).

I wrote this code:

struct A
{
  int t;
};

char *buf = new char[sizeof(A)];

A *ptr = reinterpret_cast<A*>(buf);
ptr->t = 1;

A *ptr2 = reinterpret_cast<A*>(buf);
cout << ptr2->t;

I think these rules do not apply here:

  • T2 is a (possibly cv-qualified) dynamic object type
  • T2 and T1 are both (possibly multi-level, possibly cv-qualified at each level) pointers to the same type of T3 (starting with C ++ 11)
  • T2 , ( ): /, .
  • T2 - (, cv-)
  • T2 (, cv-)
  • T2 char char

-, . ? ?

, connect (man 2 connect) struct sockaddr?

   int connect(int sockfd, const struct sockaddr *addr,
               socklen_t addrlen);

Eg. struct sockaddr_in, struct sockaddr. , ?

+4
1

, , , char* A*: , A* A* , , .

- :

#include <new>
#include <iostream>

struct A
{
  int t;
};

char *buf = new char[sizeof(A)];

A* ptr = new (buf) A;
ptr->t = 1;

// Also valid, because points to an actual constructed A!
A *ptr2 = reinterpret_cast<A*>(buf);
std::cout << ptr2->t;

( , , !).

. . , , placement- new , char.

( ++ 11) std::aligned_storage :

using Storage = std::aligned_storage<sizeof(A), alignof(A)>::type;
auto* ptr = new Storage;

, , :

Storage data;

placement- :

new (ptr) A();
// or: new(&data) A();

:

*reinterpret_cast<A*>(ptr);
// or: *reinterpret_cast<A*>(&data);

:

#include <iostream>
#include <new>
#include <type_traits>

struct A
{
  int t;
};

int main()
{
    using Storage = std::aligned_storage<sizeof(A), alignof(A)>::type;

    auto* buf = new Storage;
    A* ptr = new(buf) A();

    ptr->t = 1;

    // Also valid, because points to an actual constructed A!
    A* ptr2 = reinterpret_cast<A*>(buf);
    std::cout << ptr2->t;
}

( )

, ++ 17, ; . cppreference std::launder.

, , A , , ; , A , buf , - , .

+4

Source: https://habr.com/ru/post/1599546/


All Articles