c++ - Swapping `std::aligned_storage` instances containing non-trivially-copyable types - undefined behavior? -


ideone link

#include <iostream> #include <type_traits>    using namespace std;  // non-trivially-copyable type. struct ntc {     int x;           ntc(int mx) : x(mx) { }         ~ntc() { cout << "boop." << x << endl; } };  int main()  {     using = aligned_storage_t<sizeof(ntc), alignof(ntc)>;      // create 2 `std::aligned_storage` instances     // , "fill" them 2 "placement-new-constructed"      // `ntc` instances.     as1, as2;             new (&as1) ntc{2};     new (&as2) ntc{5};      // swap `aligned_storages`, not contents.     std::swap(as1, as2);      // explicitly call `~ntc()` on contents of     // aligned storage instances.     ntc& in1{*static_cast<ntc*>(static_cast<void*>(&as1))};     ntc& in2{*static_cast<ntc*>(static_cast<void*>(&as2))};          in1.~ntc();     in2.~ntc();      return 0; } 

is above code undefined behavior?

here's think that's happening:

  • ntc non-trivially-copyable type.
  • i'm creating 2 memory locations suitable store ntc objects (std::aligned_storage).
  • i construct 2 ntc instances directly memory locations.
  • std::aligned_storage instances podtypes.

    this means type compatible types used in c programming language, can manipulated using c library functions: can created std::malloc, can copied std::memmove, etc, , can exchanged c libraries directly, in binary form.

  • since aligned storage instances pod types, should allowed move/swap/copy them around.
  • swapping aligned storage instances means take bytes aligned storage , swap them bytes aligned storage b.
  • doing not call destructor/copy-constructor of internally stored ntc objects.

are of points incorrect? if undefined behavior occur, in part of program occur? , why?


new potentially-correct/incorrect information (gathered deleted answer):

am making mistake in these new assumptions?

directly accessing bytes of buffer after non-trivially-copyable type has been placed in bad idea, not undefined yet.

attempting access buffer after swapping ntc violates aliasing rules, [basic.lval]p10:

if program attempts access stored value of object through glvalue of other 1 of following types behavior undefined:

(10.1) -- dynamic type of object,

[....]

copying trivially copyable type through memcpy or equivalent implied preserve dynamic type. no such implication made non-trivially copyable types, after swapping, no longer have ntc objects access.


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -