NUMCXX  0.13.20181108
Numerical library for small projects and teaching purposes
04-cxx-style-sharedptr.cxx
Go to the documentation of this file.
1 #include <cstdio>
9 #include <vector>
10 #include <memory>
11 
12 // The smart pointer is passed by value, it contains
13 // a pointer to the object.
14 void initialize(std::shared_ptr<std::vector<double>> x)
15 {
16  // Here we need to dereference the smart pointer
17  // in order to access the data. This looks a bit
18  // confusing...
19  const int n=x->size();
20  for (int i=0;i<n;i++) (*x)[i]= 1.0/(double)(1+n-i);
21 }
22 
23 double sum_elements(std::shared_ptr<std::vector<double>> x)
24 {
25  double sum=0;
26  for (int i=0;i<x->size();i++)sum+=(*x)[i];
27  return sum;
28 }
29 
30 int main()
31 {
32  const int n=12345678;
33 
34  // This declares and creates a shared pointer from an object
35  // allocated with new. Quite cumbersome...
36  std::shared_ptr<std::vector<double>> x=std::shared_ptr<std::vector<double>>(new std::vector<double>(n));
37  initialize(x);
38  double s=sum_elements(x);
39  printf("sum=%e\n",s);
40 
41  // The shared pointer is destroyed, reference counter decremented
42  // and, as it becomes 0, the allocated memory is released.
43  return 0;
44 }
double sum_elements(std::shared_ptr< std::vector< double >> x)
void initialize(std::shared_ptr< std::vector< double >> x)
int main()
A::value_type sum(const A &a)
Sum of array or expression.
Definition: util.ixx:81