Skip to content

Instantly share code, notes, and snippets.

@jirihnidek
Created November 7, 2014 12:43
Show Gist options
  • Save jirihnidek/cffb83357c317e695004 to your computer and use it in GitHub Desktop.
Save jirihnidek/cffb83357c317e695004 to your computer and use it in GitHub Desktop.
Example of C++ shared pointers
#include <iostream>
#include <memory>
#include <assert.h>
using namespace std;
template <class Value>
class Output
{
public:
Output(int count) {
this->data_ = new Value[count];
this->count_ = count;
for(int i = 0; i < count; i++) {
this->data_[i] = (Value)i;
}
};
~Output() { delete[] this->data_; }
Value getOutitem(int i) {
assert(i >= 0 && i < this->count_);
return this->data_[i];
}
private:
int count_;
Value *data_;
};
class Pokus
{
public:
Pokus() { vec_[0] = vec_[1] = vec_[2] = 0.0; };
Pokus(double vec[3]) {
this->vec_[0] = vec[0];
this->vec_[1] = vec[1];
this->vec_[2] = vec[2];
}
~Pokus() {};
double getVecComp(int i) {
assert(i>=0 && i<=2); return this->vec_[i];
};
private:
double vec_[3];
};
int main(int argc, char const *argv[])
{
double vec[3] = {1.1, 2.2, 3.3};
auto sp1 = make_shared<Pokus>(vec);
auto sp2 = make_shared<Output<double>>(10);
cout << "Vector[0]: " << sp1->getVecComp(0) << endl;
cout << "Output[5]: " << sp2->getOutitem(5) << endl;
return 0;
}
@jirihnidek
Copy link
Author

To compile this file with C++ source code using GCC use following command:

g++ -std=c++0x ./shared_pointers.cc

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