lundi 29 janvier 2018

Is accessing "object representation" using the constructor string_view(const CharT*, size_type) defined char aliasing or undefined behavior?

Let we have this object

constexpr uint64_t lil_endian = 0x65'6e'64'69'61'6e; // 00en dian
    // a.k.a. Clockwise Rotated Endian which allocates like
    // char[8] = { 'n','a','i','d','n','e','\0','\0' }

It is believed that memcpy is there also to help pun type like this

char arr[sizeof(lil_endian)];
auto p1 = std::addressof(arr[0]);
std::memcpy(p1, &lil_endian, sizeof(lil_endian) ); // defined?
auto sv1 = std::string_view(p1, sizeof(lil_endian) );
std::string str1(sv1.crbegin()+2, sv1.crend() );
std::cout << str1        << "\n"
          << str1.size() << "\n";

everything is like expected:

endian
6


The matter of fact is that even with string_view alone, we access the object by char anyway, which char is one of the allowance three char, unsigned char, std::byte aliases.

So can we just skip the redundant copy part of the code, like this?

auto p2 = reinterpret_cast<const char *>
                ( &lil_endian );
auto sv2 = std::string_view(p2, sizeof(lil_endian) ); // is this "char" aliasing?
std::string str2(sv2.crbegin()+2, sv2.crend() );   
std::cout << str2        << "\n"
          << str2.size() << "\n";

}

output:

endian
6

Is the constructor string_view(const CharT*, size_type) "char" aliasing by strict aliasing [basic.val] § 11 in N4713 page 82

godbolt

wandbox

Aucun commentaire:

Enregistrer un commentaire