开发者

what is the Different categories of pointers?

Can any body explains about the different categories of pointer(like wil开发者_开发百科d pointers)?


  • Valid pointer: one pointing to a real object in memory
  • Invalid pointer: one pointing to memory that is not what it is supposed to be.
  • NULL pointer: A pointer whose value is 0 and thus points at nothing.
  • Dangling pointer (also sometimes wild pointer): one pointing to memory that has been deleted/freed.
  • Smart pointer: Not really a pointer at all, but rather an object which acts like a pointer, but manages the memory for you.


There are also function pointers, which point to code rather than objects. And pointers to members, which require an instance of a class to fully dereference. And pointers to member functions, which point to code and requires and an instance of a class to fully dereference.

There are several different types of smart pointers as well. These are used to wrap up dynamic memory allocations, and track ownership of the underlying data. When nobody owns the data any more, the dynamic memory is automatically released. The three biggies here are scoped pointers, shared pointers, and weak pointers. Scoped pointers only have one owner, and when they go out of scope they get deleted [see std::auto_ptr in C++03 and std::unique_ptr in C++0x]. Shared pointers can have many owners, and the memory doesn't get freed until all the owners are done with them. Weak pointers are a form of these, but they don't maintain strict ownership at all times; they request ownership when they need it, and that request is denied if the corresponding shared pointer has run out of owners.


...adding orthogonally to Steve's answer -

  • pointer to a variable (int*, char*, also void* which is a special pseudo-type which must always be cast before dereferencing. Also pointers to pointers.)
  • pointer to a function (void(*)(), int(*)(int)) and so on.)

The distinction is important because one family can't be cast into the other, and vice versa.


You could also add another level of categorization and sort pointers according to their "constness":

Pointer to a const - You can change to pointer, but not what it points to.

Example:

int i = 42;
const int* pi = &i;

or

int i = 42;
int const* pi = &i;

Const pointer - You can't change what the pointer points to.

Example:

int i = 42;
int* const pi = &i;

Const pointer to a const - You can't change what the pointer points to and you can't change the pointer itself.

Example:

int i = 42;
const int* const pi = &i;


Here is your answer:

C++ Pointers

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜