Is copying trivially copyable objects always defined in C++14?

后端 未结 2 1189
借酒劲吻你
借酒劲吻你 2021-01-22 13:06

For a trivially copyable type T consider:

void f(T z)
{
   T a;
   T b;
   std::memcpy(&b, &a, sizeof(T));

   a = z;
   b = z;         


        
2条回答
  •  心在旅途
    2021-01-22 13:33

    There are a couple things at play here:

    • an expression evaluating to an indeterminate value causes undefined behavior, with certain exceptions (8.5p12)
    • unsigned char (and possibly char, if unsigned) is the exception
    • variables with automatic storage duration and whose types have trivial default initialization initially have indeterminate values (5.3.4p17)

    This means that

    • unsigned char is fine, no matter whether using memcpy or memmove or copy-assignment or copy-constructor
    • memcpy and memmove is presumably fine for all types, because the result is not "produced by an evaluation" (to meet this requirement, an implementation can use unsigned char internally, or take advantage of implementation-specific guarantees made for other types)
    • copy-constructor and copy-assignment for other types will fail if the right-hand-side is an indeterminate value

    Of course, even the valid methods for copying an indeterminate value create another indeterminate value.


    Paragraph numbers correspond to draft n4527

提交回复
热议问题