How bad are bare pointers?

Are pointers to things that are otherwise safe in C ++?

Until now, I used STL containers (and in one case an array, but this is another question) for all of my dynamic memory needs, so I don’t need to explicitly use the keyword new, I also recklessly used simple pointers like 't21> to refer to things. Now I'm reading about smart pointers (I cut my teeth in Java, so I never had to worry about it), and generally accepted wisdom seems like “bare pointers are bad, don't use them.”

So to what extent am I worried? Can I safely continue to use bare pointers if they point to other conditions of destruction? This is something I can escape with, but should be avoided in the future? Or is it a disaster in the making that I have to fix post-haste?

+3
source share
5 answers

White pointers are safe on their own, it is the wrong use of them, which is dangerous (and you can easily get carried away). Smart pointers are great and all, but some ( shared_ptr) include reference counting, resulting in a performance penalty. You should try to use smart pointers where applicable, but using AFAIK with pointers is not considered a terrible mistake.

STL, , .

+6

, , , , , -, .

, . , , , , , , .

, "". , - "":).

- , , , " ". , , , , , ( ), raw-, smart .

unique_ptr<> , , NULL . .

shared_ptr<> , , , .

, , , .

+1

, " , " : " , ".

- , . , , . , , , , , vector ..

:

  • : T*, ,
  • : shared_ptr<T>,
  • : unique_ptr<T, Del>,

, , , , .

+1

, . , .

(.. ), , ( ", , , ".). (.. ), .

, (, , ). , , , , , .

, , , . , , /, , , , . . , , , / .

0

, new delete . . , , , , Valgrind.

, new [], delete [] , , new, delete.

Remember to mix new- deletewith malloc- freeor with new[]- delete[], because these functions are not designed to work with each other, for example, never do this:

int *a = (int*)malloc(10*sizeof(int));
delete a;

but this one

int *a = new int[10];
delete[] a;

As Tibor said, using a pointer is not so bad, but, as always, “great responsibility comes with great power”: P

-2
source