vector-array.cc 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // -*- mode: c++; coding: utf-8 -*-
  2. // ra-ra/test - Comparison of ra::ptr(std::vector) vs ra::ptr(std::array)
  3. // (c) Daniel Llorens - 2021
  4. // This library is free software; you can redistribute it and/or modify it under
  5. // the terms of the GNU Lesser General Public License as published by the Free
  6. // Software Foundation; either version 3 of the License, or (at your option) any
  7. // later version.
  8. // This checks an alternate version of ra::Vector that doesn't work. Cf [ra35] in ra-9.cc.
  9. /*
  10. <PJBoy> lloda, ok I'm convinced it's because Vec is trivially copyable for
  11. std::array<int, n> [22:00]
  12. <PJBoy> after some help from the C++ discord :D [22:01]
  13. <PJBoy> there's some standardese wording for it
  14. https://eel.is/c++draft/class.temporary#3 [22:02]
  15. <ville> well that's fun [22:05]
  16. <PJBoy> tldr being something like, trivially copyable+moveable types can be
  17. arbitrarily copied without your consent [22:07]
  18. <lloda> thx PJBoy
  19. <PJBoy> which means the iterator can never be assumed to be valid after
  20. passing the array up or down the call stack [22:08]
  21. <PJBoy> explicitly deleting or defining the copy/move ctors is the most direct
  22. workaround
  23. */
  24. #include <iostream>
  25. #include <array>
  26. #include <vector>
  27. using std::cout, std::endl;
  28. template <class V>
  29. struct Vec
  30. {
  31. V v;
  32. decltype(v.begin()) p = v.begin();
  33. };
  34. template <class V>
  35. constexpr auto
  36. vec(V && v)
  37. {
  38. return Vec<V> { std::forward<V>(v) };
  39. }
  40. int main()
  41. {
  42. auto f1 = [] { return std::array {7, 2}; };
  43. auto f2 = [] { return std::vector {5, 2}; };
  44. auto v1 = vec(f1());
  45. auto v2 = vec(f2());
  46. cout << (v1.v.begin()==v1.p) << endl; // unfortunate
  47. cout << (v2.v.begin()==v2.p) << endl;
  48. return 0;
  49. }