fork(1) download
  1. #include <initializer_list>
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. struct something
  6. {
  7. std::vector < int > _Value;
  8.  
  9. something( const std::initializer_list < int >& _List ) : _Value( { _List } ) {}
  10. std::vector < int >& get_vector() { return ( _Value ); }
  11. ~something() { std::cout << "destructor" << std::endl; }
  12. };
  13.  
  14. int main()
  15. {
  16. // 危険なコード
  17. for( auto e : something { 1,2,3,4,5,6,7,8,9,0 }.get_vector() ) // get_vectorは内部に持つvectorへの参照を返す
  18. { // 破棄されたオブジェクトへの参照
  19. std::cout << e;
  20. }
  21. std::cout << std::endl;
  22.  
  23. // 安全なコード
  24. for( auto e : std::vector < int > { 1,2,3,4,5,6,7,8,9,0 } )
  25. { // 一時オブジェクトはキャプチャされ延命されている
  26. std::cout << e;
  27. }
  28. }
  29.  
Success #stdin #stdout 0s 3228KB
stdin
Standard input is empty
stdout
destructor
0234567890
1234567890