Boost logo

Boost Users :

Subject: [Boost-users] shared_ptr vs pass object by reference
From: Max S. Kaznady (max.kaznady_at_[hidden])
Date: 2010-07-28 09:02:41


If I can pass the object by reference to a function, then is there a
need to use shared pointers? I demonstrated 3 ways of passing by
reference below, but my main concern is just passing a shared_ptr by
value VS passing an object reference.

#include<iostream>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
#include <boost/shared_ptr.hpp>

// If I can just pass an object like this, this do I really need to
use shared pointers?
void pass_obj_ref(boost::numeric::ublas::matrix<double> &m) {
  for (unsigned i = 0; i < m.size1(); ++i)
    for (unsigned j = 0; j < m.size2(); ++j)
      m(i, j) = 3 * i + j;
}

// This is the correct way to pass a pointer, because we create a copy
of the pointer inside
// the function and we cannot do something to the pointer outside of
the scope of the function call
void pass_ptr_by_val(
    boost::shared_ptr<boost::numeric::ublas::matrix<double> > const m) {
  for (unsigned i = 0; i < m->size1(); ++i)
    for (unsigned j = 0; j < m->size2(); ++j)
      (*m)(i, j) = 3 * i + j;
}

// This is not good since we can modify the pointer within the
function, and then
// another developer wouldn't know what to do after the function call
void pass_ptr_by_ref(
    boost::shared_ptr<boost::numeric::ublas::matrix<double> > const &m) {
  for (unsigned i = 0; i < m->size1(); ++i)
    for (unsigned j = 0; j < m->size2(); ++j)
      (*m)(i, j) = 3 * i + j;
}

int main(void) {
  unsigned s1 = 10, s2 = 20;
  // regular matrix
  boost::numeric::ublas::matrix<double> m1(s1, s2);
  // pass pointer by value
  boost::shared_ptr<boost::numeric::ublas::matrix<double> > m2(
      new boost::numeric::ublas::matrix<double>(s1, s2));
  // pass pointer by reference
  boost::shared_ptr<boost::numeric::ublas::matrix<double> > m3(
      new boost::numeric::ublas::matrix<double>(s1, s2));

  pass_obj_ref(m1);
  pass_ptr_by_val(m2);
  pass_ptr_by_ref(m3);

  std::cout << m1 << std::endl;
  std::cout << *m2 << std::endl;
  std::cout << *m3 << std::endl;
}


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net