Are pointers to things that are allocated in other ways reasonably safe in C++?
Up to this point, I’ve been using STL containers (and in one case, an array, but that’s another question) for all my dynamic memory needs, so I hadn’t needed to explicitly use the new keyword. I’ve also been blithely using plain ol’ int *foo type pointers to reference things. Now I’m reading about smart pointers (I cut my teeth on Java, so I never had to worry about this before) and the conventional wisdom seems to be “bare pointers are bad, don’t use them.”
So how much trouble am I in? Can I safely keep using bare pointers, so long as the things they point to have other destruction conditions? Is it something I can get away with, but should avoid in the future? Or is it a disaster in the making that I should go fix post-haste?
Bare pointers are safe per se, it is the incorrect usage of them that is dangerous (and you can get carried away easily). Smart pointers are nifty and all, but some (
shared_ptr) involve reference counting, which incurs a performance penalty. You should try to use the smart pointers where applicable but AFAIK using pointers is not considered a horrible mistake.You should be careful when referencing members of the STL containers as their addresses can change during relocation leaving you with strange bugs.