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
#include
#include
// 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 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 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 m2(
new boost::numeric::ublas::matrix<double>(s1, s2));
// pass pointer by reference
boost::shared_ptr 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;
}