Skip to content

Instantly share code, notes, and snippets.

@chunkyguy
Last active July 19, 2018 23:08
Show Gist options
  • Save chunkyguy/5986168 to your computer and use it in GitHub Desktop.
Save chunkyguy/5986168 to your computer and use it in GitHub Desktop.
std::unique_ptr: Creating unique_ptr to hold array of pointers to something.
// unique_ptr
// Case 1: Array of type
// Case 2: Array of pointer to type
#include <iostream>
#include <memory>
class Bar {
public:
Bar(float b) : bb(b) {
std::cout << "Bar" << std::endl;
}
~Bar() {
std::cout << "~Bar" << std::endl;
}
float bb;
};
int main() {
//Case 1
std::unique_ptr<int []> foo(new int[10]);
for (int i = 0; i < 10; ++i) {
foo[i] = i*i;
}
for (int i = 0; i < 10; ++i) {
std::cout << "foo[" << i << "] = " << foo[i] << std::endl;
}
//Case 2
// Bar** boo = new Bar* [10]
std::unique_ptr<Bar* [], void(*)(Bar**)> boo(new Bar*[10], [](Bar** boo_ptr){
for(int i = 0; i < 10; ++i) {
delete boo_ptr[i];
}
delete [] boo_ptr;
});
for(int i = 0; i < 10; ++i) {
boo[i] = new Bar(i * 0.5f);
}
for(int i = 0; i < 10; ++i) {
std::cout << "bar[" << i << "] = " << boo[i]->bb << std::endl;
}
return 0;
}
@chunkyguy
Copy link
Author

//OUTPUT
whackylabs:Projects sidharthjuyal$ clang++ unique_ptr_arr.cpp -o unique_ptr_arr -std=c++11 -stdlib=libc++ && ./unique_ptr_arr
foo[0] = 0
foo[1] = 1
foo[2] = 4
foo[3] = 9
foo[4] = 16
foo[5] = 25
foo[6] = 36
foo[7] = 49
foo[8] = 64
foo[9] = 81
Bar
Bar
Bar
Bar
Bar
Bar
Bar
Bar
Bar
Bar
bar[0] = 0
bar[1] = 0.5
bar[2] = 1
bar[3] = 1.5
bar[4] = 2
bar[5] = 2.5
bar[6] = 3
bar[7] = 3.5
bar[8] = 4
bar[9] = 4.5
~Bar
~Bar
~Bar
~Bar
~Bar
~Bar
~Bar
~Bar
~Bar
~Bar

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment