Skip to content

Instantly share code, notes, and snippets.

@piyo7
Last active August 29, 2015 14:16
Show Gist options
  • Save piyo7/36b39f612baeb739c23b to your computer and use it in GitHub Desktop.
Save piyo7/36b39f612baeb739c23b to your computer and use it in GitHub Desktop.
参照を返すゲッターで範囲for文を回したらバグった ref: http://qiita.com/piyo7/items/4c2ba618a58c3bb72c0c
#include <iostream>
#include <vector>
// vectorのラッパークラス
template<typename T>
class Foo {
std::vector<T> data_;
public:
Foo(const std::vector<T>& data) : data_(data) {}
// コピーのコストを嫌ってconst参照で返すゲッター
const std::vector<T>& data() const { return data_; }
};
// テンプレート引数を省略するためのファクトリ
template<typename T>
Foo<T> make_foo(const std::vector<T>& data) {
return Foo<T>(data);
};
int main() {
std::vector<int> is = {0, 1, 2};
for (int i : make_foo(is).data()) std::cout << i << ", "; // 何が起こるか分からない!!!
std::cout << std::endl;
std::vector<int> is2 = make_foo(is).data(); // コピー代入
for (int i : is2) std::cout << i << ", "; // 大丈夫!!!
std::cout << std::endl;
return 0;
}
12396288, 0, 2,
0, 1, 2,
std::vector<int>* ptr = &make_foo(is).data();
{
auto && __range = range_expression;
for (auto __begin = begin_expr, __end = end_expr; __begin != __end; ++__begin) {
range_declaration = *__begin;
loop_statement
}
}
{
auto && __range = range_expression;
for (auto __begin = begin_expr, __end = end_expr; __begin != __end; ++__begin) {
range_declaration = *__begin;
loop_statement
}
}
{
const std::vector<int>& range = make_foo(is).data();
for (auto itr = range.begin(), end = range.end(); itr != end; ++itr) {
int i = *itr;
std::cout << i << ", ";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment