4

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 char*, size_type) "char" aliasing by strict aliasing ([basic.val]/11) -- § 8.2.1 ¶ 11 in N4713 page 82

godbolt

wandbox

sandthorn
  • 2,770
  • 1
  • 15
  • 59
  • 1
    Do you not see the explicit exception granted to `char`, `unsigned char` and `std::byte`? It's right there in the section you link to at 11.8. Aliasing through a `const char*` is perfectly legal and well defined. – Nathan Ernst Jan 29 '18 at 19:30
  • You seem to have answered your question in the question. Which part of this are you unsure of? Whether `string_view` internally is just a `const char*` or whether access via `const char*` is *really* access via `char`? – Barry Jan 29 '18 at 19:35
  • @NathanErnst I'm not sure. Because last month the both answers of [47921786](https://stackoverflow.com/q/47921786) didn't confirm that this is defined. – sandthorn Jan 30 '18 at 06:17
  • @Barry You may flag this as duplicate but the thing is that the both answers of [47921786](https://stackoverflow.com/q/47921786) didn't confirm that this is defined. – sandthorn Jan 30 '18 at 06:19
  • @sandthorn What? I'm trying to understand what your *question* is. What is the source of confusion? – Barry Jan 30 '18 at 13:28
  • @Barry The source of my confusion is that both answers of [47921786](https://stackoverflow.com/q/47921786) seem **not certained enough** to say like "it's okey to reinterpret pointer to char then wrap around `trivially_copyable`s with `string_view` constructor". Well, if you think it's pretty okey, you can write some answer to this or to [47921786](https://stackoverflow.com/q/47921786) or even both! ...would be great. I guess we just need an expert to confirm us about this. – sandthorn Feb 07 '18 at 15:16

0 Answers0