Uninitialized pointers in code

后端 未结 8 2285
旧巷少年郎
旧巷少年郎 2020-11-30 03:15

I am learning C++ and I came to know that pointers if left uninitialized could point to random locations in memory and create problems that memory might be used by some othe

8条回答
  •  死守一世寂寞
    2020-11-30 03:56

    In C++, you should generally avoid plain old pointers altogether. Standard library classes, smart pointers (until C++0x only in various libraries like Boost or Loki) and references can and should be used in most places instead.

    If you can't avoid pointers, it's indeed preferable to declare them with initializations, which in most cases should not be NULL, but the actual target value, because in C++ you can mix declarations and expressions freely, so you can and should only declare the variable at the point you have meaningful value for it.

    That's not the case with C where you have to use pointers a lot and all variables have to (or had to before C99; I am not exactly sure) be declared at the begining of a scope. So many people still have bad habits from C that are not appropriate for C++.

提交回复
热议问题