list9.cc 2.3 KB

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