gsl - C++ strange behaviour with function call by value -


i have object class interface matrix struct found in gnu scientific library

typedef double real_t; typedef unsigned short index_t; class matrix {         gsl_matrix* m;     public:         matrix(index_t rows, index_t columns, real_t val); }  matrix::matrix(index_t rows, index_t columns, real_t val) {     m=gsl_matrix_alloc(rows,columns);     gsl_matrix_set_all(m, val);     return; }  index_t matrix::rows(void) {     return m->size1; }  index_t matrix::columns(void) {     return m->size2; } 

the problem if use function taking matrix object value one:

void test_function(const matrix m){}; 

and use in program one

int main() {     matrix m(4,4,1);     cout << m.rows() << '\t' << m.columns() << endl;     test_function(m);     cout << m.rows() << '\t' << m.columns() << endl; } 

i surprisingly obtain number of rows of matrix object m modified function test_function garbage value, if put keyword const before argument , call made value. strangest thing if use function makes use of call reference one:

void test_function(const matrix &m){}; 

nothing happens , seems right.

as far know, call value shouldn't able modify argument of function, if function nothing in case , if explicitly use keyword const before argument name in function prototype...

any appreciated.

edit:

i have defined copy constructor matrix class as

matrix& matrix::operator= (const matrix& src) {     gsl_matrix_memcpy(m,src.m);     return *this; } 

which complete copy (i guess) of gsl_matrix struct

edit:

ok, think i've understood: call value function creates shallow copy object contains pointer real object, when test_function terminates local variables destroyed, destructor of matrix class (which defined omitted here sake of brevity) called, in way object in main (to local m points to) destroyed local variable.. anyway solved problem defining proper copy constructor performs complete (deep) copy of object , using call reference should better heavy computation. lot help!

when pass argument value, compiler calls one-argument copy constructor create value in function. if not provide copy constructor, compiler generates 1 you.

in example above, compiler generated copy constructor makes shallow copy of inner matrix pointer. when newly generated matrix in function goes out of scope, shallow copied pointer gets deleted also. guess reason.

you check providing copy constructor not copy gsl_matrix pointer.


Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -