list9.cc 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // -*- mode: c++; coding: utf-8 -*-
  2. // ra-ra/test - Demo new warning in 9.1
  3. // (c) Daniel Llorens - 2019
  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. /*
  9. https://gcc.gnu.org/onlinedocs/gcc-9.1.0/gcc/C_002b_002b-Dialect-Options.html#index-Winit-list-lifetime
  10. When a list constructor stores the begin pointer from the initializer_list
  11. argument, this doesn’t extend the lifetime of the array, so if a class variable
  12. is constructed from a temporary initializer_list, the pointer is left dangling
  13. by the end of the variable declaration statement.
  14. <lloda> I don't understand this warning in 9.1 [13:06]
  15. <lloda> https://wandbox.org/permlink/RTIL3P6nRanIx4Sd
  16. <lloda> I've read
  17. <lloda>
  18. https://gcc.gnu.org/onlinedocs/gcc-9.1.0/gcc/C_002b_002b-Dialect-Options.html#index-Winit-list-lifetime
  19. <lloda> the last item
  20. <lloda> but doesn't it make a difference that I use p(a.begin()) and not
  21. p(x.begin()) ?
  22. <lloda> either gives the same warning
  23. <redi> no, it makes no difference [13:07]
  24. <redi> a and x are both just pointers to the same underlying array
  25. <redi> the array is not owned by the initializer_list
  26. <redi> do not store an initializer_list like that. ever. it's not a container.
  27. <lloda> fair :O [13:08]
  28. <lloda> then the { p = a.begin(); } should warn as well?
  29. <redi> it's for INITIALIZING, not storing data
  30. <redi> yes, ideally that would warn too
  31. <redi> your comment says "works" but it's wrong. It doesn't work any
  32. differently, it just doesn't warn. [13:09]
  33. */
  34. // /opt/gcc-9.1/bin/g++ -o list9 -std=c++17 -Wall -Werror list9.cc
  35. #include <utility>
  36. struct Bar
  37. {
  38. std::initializer_list<int> a;
  39. decltype(a.begin()) p;
  40. // Bar(std::initializer_list<int> x): a(x), p(a.begin()) {} // warns
  41. Bar(std::initializer_list<int> x): a(x) { p = a.begin(); } // doesn't (but same thing)
  42. };
  43. template <class T>
  44. struct Foo
  45. {
  46. Foo(std::initializer_list<int> s): Foo(Bar(s)) {}
  47. };
  48. int main() {}