C++ outline and interview questions (2): Pointers

来源:互联网 发布:网站美工教程 编辑:程序博客网 时间:2024/04/29 17:50

2.1. Contents

2.1.1There are two main issues of pointers: dangling pointers or memory leaking.

2.1.2Generally speaking, pointers are not safe. There are two main ways to solvethis issue: use reference or smarter pointers.

2.1.3Pointer and reference:

(3.1)definitions:

Pointer:a variable that stores the address of some object (system defined or customdefined).

Reference:an atlas of some object.

(3.2)similarities and differences:

Term

pointer

Reference

Can be NULL?

Yes

No

Can be re-set to another object?

Yes

No

Can be used without initialization?

Yes (a dangling value, may be dangerous)

No

Can be mangling by const?

Yes (two types of const, const object or const value)

No

The return value of sizeof

4 (the size of an int variable, the address)

The size of object.

Work with ++ / --

Move to the next address (p += sizeof(type))

The value of the object increments 1.

Can be used to call the object itself?

Yes (Use -> to call the members)

Yes (Use . to call the members like using object itself)

Occupy memory?

Yes

No

(3.3)at what time, we should use pointers instead of references? (Very important!!!)

(1)A pointer that has not been initialized. (A ref must be initialized)

(2)A NULL pointer. (A ref cannot be set to NULL obj)

(3)We need to change the relation of a pointer to an object.

(4)When we need to callback method (use the pointer to a given function). Callbackmeans call a function as long as the conditions are ready. Since the actualspot to call the function is not known before it is called, we should pass anentrance to the given function without changing the header files.

2.1.4Reference count – This is the key technique to construct smart pointers.

2.1.5Array and pointer:

(1)If pass an array to a function, we should use same length of array. But, thereis no such restriction to a pointer. Then, it is freer to use a pointer passingas a parameter.

(2) typea[]; a is of the type of type* const,i.e., the value of a cannot be changed.

Thiscan be used to initialize a pointer, i.e., type *p_a = a;This is the reason why char *p_str_head = “hello world”; works, buttype *& p_a = a does not work.

(3)Arithmetic: p + i and a + i are all legal, but a++ is NOT, since its valuecannot change.

(4) A potential issue: since the length ofarray (the array pointed by a pointer) does not come with the array, the index(or the pointer) is very easily to access the value in the address out of therange. (Solution: use vector.)

2.1.6memset: memset is a C-style function which is used for filling one initialvalue to an array of objects (esp. for filling a NULL value to an array ofpointer). This function is highly not recommended for using in C++ code, sinceit will not call ctor.

2.2. Questions

Q: What is pointer?

A: A variablethat stores the address of some object (system defined or custom defined). Apointer can be NULL. Usually, a pointer should be initialized before it isused. In debug and release modes, a pointer will be assigned by differentvalues (0xccc and random value).

Q: What is reference?

A: A reference isan alias of an object (system defined or custom defined). It behaves same asthe object it refers. A reference should be valid initialized before.

Q: What does mean “p + 1”?

A: The address of the object placed nextto the object pointed by the pointer p. in other words, p + 1 is equivalentwith p + sizeof(type).

Q: What is a dangling pointer?

A: A dangling pointer arises when youuse the address of an object after its lifetime is over. This may occur insituations like returning addresses of the automatic variables from a functionor using the address of the memory block after it is freed.

Q: What is Memory Leak? How to detect them?How to prevent them?

A: Memory which has no pointer pointingto it and so there is no way to delete or reuse it causes Memory leak. Theessential reason of memory leaking is because the pointer will be deleted whento exit the scope of this pointer but the memory it points will not be freedautomatically.

Inwindows, use visual studio, and in Linux, use valgrind.

Theretwo usual ways: (1) write in pairs (But, this need to be sure that the programwill not exit with exception) (2) use smart pointers.

Q: What is auto pointer?

A: The simplest example of a smartpointer is auto_ptr, which is included in the standard C++ library. AutoPointer only takes care of Memory leak and does nothing about dangling pointersissue. You can find it in the header . Here is part of auto_ptr's implementation,to illustrate what it does:

template<typename T> class auto_ptr

{

T* ptr;

public:

explicit auto_ptr(T* p = 0) : ptr(p) {}

~auto_ptr() {delete ptr;}

T& operator*() {return *ptr;}

T* operator->() {return ptr;}

//...

};

Asyou can see, auto_ptr is a simple wrapper around a regular pointer. It forwardsall meaningful operations to this pointer (dereferencing and indirection). Itssmartness in the destructor: the destructor takes care of deleting the pointer.

auto_ptris not used in C++ 11.

Q: What issue do auto_ptr objects address?

A: If you use auto_ptr objects youwould not have to be concerned with heap objects not being deletedeven if the exception is thrown.

Q: What is a smart pointer?

A: A smart pointer is a C++ class thatmimics a regular pointer in syntax and some semantics, but it does more.Because smart pointers to different types of objects tend to have a lot of codein common, almost all good-quality smart pointers in existence are templated bythe pointee type, as you can see in the following code:

template

classSmartPtr

{

public:

explicitSmartPtr(T* pointee) : pointee_(pointee);

SmartPtr&operator=(const SmartPtr& other);

~SmartPtr();

T&operator*() const

{

...

return*pointee_;

}

T*operator->() const

{

...

returnpointee_;

}

private:

T*pointee_;

...

};

Smartpointer aggregates a pointer to T in its member variable pointee_. That's whatmost smart

pointersdo. In some cases, a smart pointer might aggregate some handles to data andcompute

thepointer on the fly.

Thetwo operators give SmartPtr pointer-like syntax and semantics. That is, you canwrite

classWidget

{

public:

voidFun();

};

SmartPtrsp(new Widget);

sp->Fun();

(*sp).Fun();

Asidefrom the definition of sp, nothing reveals it as not being a pointer. This isthe mantra of

smartpointers: You can replace pointer definitions with smart pointer definitionswithout

incurringmajor changes to your application's code. You thus get extra goodies with ease.

Minimizingcode changes is very appealing and vital for getting large applications to usesmart

pointers.As you will soon see, however, smartpointers are not a free lunch.

Q: Is there any problem with the following:char *a=NULL; char& p = *a;?

A: The result is undefined. You shouldnever do this. A reference must always refer to some object.

Q: What is the difference between a pointerand a reference?

A: A reference must always refer tosome object and, therefore, must always be initialized; pointers do not havesuch restrictions. A pointer can be reassigned to point to different objectswhile a reference always refers to an object with which it was initialized.

Q: What is the difference between constchar *myPointer and char *const myPointer?

A:Const char *myPointer is a non constant pointer to constant data; while char*const

myPointeris a constant pointer to non constant data.

Q: When should I use references, and whenshould I use pointers?

A: Use references when you can, andpointers when you have to.

Referencesare usually preferred over pointers whenever you don't need"reseating". This usually means that references are most useful in aclass's public interface. References typically appear on the skin of an object,and pointers on the inside.

Theexception to the above is where a function's parameter or return value needs a"sentinel" reference a reference that does not refer to an object.This is usually best done by returning/taking a pointer, and giving the NULLpointer this special significance (references should always alias objects, nota dereferenced NULL pointer).

Q: Can the function memset be used forsetting initial values for an array of objects? Give an example to support ordeny your conclusion.

A: This is HIGHLY not recommended. Seethe following example:

ClassBase{

public:

                Base() {}

                ~Base() {}

virtual void print() {}

};

ClassDerived : public Base{

public:

                Derived() {}

                ~Derived() {}

virtual void print() {}

void display() {}

};

int main()

{

                Base *p = new Derived();

                memset((void *)p, NULL, sizeof(Derived));

                p->display();  //OK: this function is called by this pointerdirectly.

                p->print();  //Error: this function is called by thevtable which is not initialized in this case.

}
0 0
原创粉丝点击