Re: pointers and references
On Nov 20, 1:17 pm, mpho <tjab...@gmail.com> wrote:
Dear all,
For types such as vector<vector<T> > are there any advantages
(pitfalls?) to using pointers over references or vice-versa? I have
this situation:
typedef vector<vector<T> > D;
void function_name(D& a, D& b, int c), where a and b will be modified.
Using references for function arguments is good practice. If you use
pointers, you will need to deal with the case that the caller gives
you a null pointer.
A bigger problem with your code is the type vector<vector<T>>.
Standard containers use value copy semantics. So if you do something
like:
vector<vector<T>> v;
v.push_back(vector<T>());
v.push_back(vector<T>());
v.push_back(vector<T>());
v.push_back(vector<T>());
Every push back has to copy the whole vector in. It's not just a
pointer copy. Also, since we are talking about vector, which is a
dynamic array, sometimes when you do a push_back it has to allocate a
new larger array and copy all of the elements over.
If you don't do a lot of push_backs or assignemnts from elements of
the outer vector you might be ok. However, in general, you should
avoid containers of containers wihtout some kind of smart pointer in
between.
For instance (using TR1/boost shared_ptr, which you already have if
you have a recent version of gcc or visual studios):
vector<shared_ptr<vector<t>>>
Alternatively, if all you are doing is creating a 2d array, just use a
single vector and wrap it in an object that does the index arithmetic
to find the right element. That's the most effiecient method.
int get_index(int x, int y) {
return x + ROW_SIZE * y;
}
vector<T> v = ...;
v[get_index(x,y)] = ...;
Inside main I call this thus:
int main(){
D u, v:
int t;
..............
function_name(a, b, t);
................
}
D is essentially a 2-d array. While the program compiles, I am
getting incomprehensible debugging (gdb) messages. This function is
long. So before I rewrite using pointers I just want to know whether
it really matters. Correctness matters of course, but do I need to
swap references for pointers in such a case and have things working
where they previously were not?
Surely the above is not something like:
int& function_name(){
int i;
..............
return i;
}
I'm not sure what you are getting at here, but you are returning a
local variable by reference, which will result in memory corruption.
Thanks all.
{ banner removed -mod }
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]