How to make C++ pointers null [closed]
While declaring all c++ pointer, all should by default be initilized to ZERO or NULL to avoid any random unwanted values. So that we can check if pointer is null that means not initilized.
thanks
In C++03, prefer ptr = 0
over ptr = NULL
(Bjarne S. says that. Read the excerpt below quoted from his site)
In C++0x, ptr = nullptr
(see this)
Bjarne Stroustrup says that,
Should I use NULL or 0?
In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days.
If you have to name the null pointer, call it nullptr; that's what it's going to be called in C++0x. Then, "nullptr" will be a keyword.
void * ptr = NULL;
or
void * ptr = 0;
You can make them NULL
by assigning NULL
or 0
to them.
C and C++ variables do not automatically initialize. If they did and you wanted to set them to a none-NULL
value, the language would not be as efficient because they would be initialized twice.
You have to do it yourself:
Foo* pFoo = NULL;
Sounds like what you actually want is a smart pointer, which will catch these kinds of bugs for you. There are several to choose from.
This is the default behavior of smart pointers such as (C++0x) std::scoped_ptr<T>
and (Boost) boost::shared_tr<T>
. If you don't use smart pointers, you get dumb behavior.
There are at least two principles of C++ that conflicts with the proposal.
1) Don't add a new feature to the language, if it already has a fetaure you can use.
int* p; // Problem here?
int* q = 0; // Fixed!
isn't big enough of a problem to change the language.
2) We don't want C code to be faster!
If
int* vp[1000000];
where faster in C than in C++, the whole internet would be full of that "benchmark".
No. That's just wasted time if you are going to initialize them anyway and the flow of your code is such that you can be sure that they are initialized before they are used.
精彩评论