Skip to content

Instantly share code, notes, and snippets.

@chikuchikugonzalez
Created October 24, 2014 15:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chikuchikugonzalez/2ca39567458509d02446 to your computer and use it in GitHub Desktop.
Save chikuchikugonzalez/2ca39567458509d02446 to your computer and use it in GitHub Desktop.
shared_ptrをvectorに入れる時の初期化方法
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#include <memory>
class Color {
public:
int r, g, b, a;
public:
Color() : r(0), g(0), b(0), a(255) {}
Color(int r, int g, int b, int a = 255) : r(r), g(g), b(b), a(a) {}
};
int main(int argc, char* argv[]) {
std::vector<std::shared_ptr<Color>> colors(256);
//colors.resize(256, std::make_shared<Color>());
std::generate(
colors.begin(),
colors.end(),
[]() -> std::shared_ptr<Color> {
return std::make_shared<Color>();
}
);
for (auto it = colors.begin(); it != colors.end(); it++) {
std::shared_ptr<Color> c = *it;
if (c) {
std::printf("[%d, %d, %d, %d] %d\n", c->r, c->g, c->b, c->a, c.use_count());
} else {
std::printf("Invalid!\n");
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment