How to answer questions about smart pointers in C + + interviews? __c++

Source: Internet
Author: User

How to answer the questions about smart pointers in C + + interviews.

1, what is the smart pointer.

2, why use the smart pointer and the principle of the smart pointer is what.

3. What are the common smart pointers under analysis?

4, to achieve a smart pointer bai. (Do not specifically write which, suggest default write: Unique_ptr (scoped_ptr))

1 . A: Smart pointer is a class that stores pointers to dynamically allocated (heap) objects, for lifetime control, to ensure that dynamically allocated objects are automatically and correctly destroyed, and to prevent memory leaks (using the destructor of the automatic invocation class to free memory). A common implementation of this technique is to use reference counting (in addition to resource monopolies, such as (AUTO_PTR), reference only, excluding numbers (weak_ptr)). A smart pointer class relates a counter to an object that the class points to, and a reference count tracks how many objects in the class share the same pointer. Initializes the pointer each time a new object of the class is created and a reference count of 1; When an object is created as a copy of another object, the copy constructor copies the pointer and increases the corresponding reference count; When an object is assigned, the assignment operator decreases the reference count of the object referred to by the left operand (if the reference count is reduced to 0, Deletes the object) and increases the reference count of the object referred to by the right operand; when the destructor is called, the constructor reduces the reference count (if the reference count is reduced to 0, the underlying object is deleted).

2 , A: Reasons:(1): Manual malloc/new out of the resources, easy to forget free/delete;

(2): The impact of the implementation of the flow of the place to pay attention to release the release of resources, easily lead to resource leaks (such as free/delete after return).

(3): Throws an exception midway, cannot release the resource. such as: int*p1=new int;int*p2=new int [10000000];delete p1;

Delele [] P2 because P2new has a large memory and if new fails, p1 can never be released.

principle: In order to solve the problem on (1), (2), (3), create a resource out of the time, to a class object to manage, when the class object declaration cycle end, automatically call the destructor release resources. In addition, operator overloading (overload * and->, etc.) can be used as a pointer.

3. Common smart pointers and parsing:

auto_ptr

(1) It is the class template provided by the C + + standard library, the Auto_ptr object points to the dynamic memory created by new, which is the owner of this memory and cannot be divided into two owners (resource exclusive). When the Auto_ptr object lifecycle ends, its destructor automatically releases the dynamic memory owned by the Auto_ptr object.

(2) Auto_ptr cannot point to an array because auto_ptr only calls delete at the time of the destructor, and the array should call delete[]. (But Uniquearray manages a continuous space, which is also a copy-proof, and functions like a vector.) )

(3) Auto_ptr can not be a container object, because it does not support copy construction and assignment (error is not easy to find), the elements in the STL container often to support the copy, assignment and other operations, in the process of auto_ptr will pass ownership, then there will be errors.

unique_ptr

It is (C++11 introduced, formerly SCOPED_PTR,SCOPED_PTR is the Boost library), does not support copy construction and assignment, but better than auto_ptr, direct assignment will compile errors (and auto_ The biggest difference of PTR is that the private declaration of copy constructors and assignment operator overloads within the class is the fault of the auto_ptr.

shared_ptr

C++11 or Boost's shared_ptr, a smart pointer based on reference counting. It can be assigned at will, until the memory reference count is 0 and the memory is freed. A ring-shaped chain structure may create a memory leak (circular reference)

Circular reference problem (often asked OH)


To solve a problem like this, C++11 introduced weak_ptr to break the circular reference.

weak_ptr

C++11 or Boost's weak_ptr, weak reference. Reference count There is a problem with referencing to form loops so that the two pointers to memory cannot be freed. You need to manually break the circular reference or use weak_ptr. As the name suggests, Weak_ptr is a weak reference, a smart pointer introduced to match the shared_ptr, which points to an object managed by shared_ptr without affecting the life cycle of the object being referred to, that is, it is referenced only, not counted. If a piece of memory is referenced at the same time by shared_ptr and weak_ptr, the memory is freed after all shared_ptr destructors, regardless of whether or not weak_ptr references the memory. So weak_ptr does not guarantee that the memory it points to must be valid, and you need to check to see if weak_ptr is a null pointer before using it.

WEAK_PTR does not overload the operator-> and operator * operators, so it is not straightforward to use objects directly through weak_ptr, typically by calling its lock function to obtain the shared_ptr example, thereby accessing the original object.

the realization of auto_ptr

Template<classt>

Class Autoptr//The transfer method of a resource manages memory, causing problems with its copy construction and assignment operators

{

Public

Autoptr (T *p=null)

:p TR (P)

{}

Autoptr (AUTOPTR<T>&AP)

:p TR (ap.ptr)

{

Ap.ptr= null;//The original object pointer is NULL after successful construction of the new object; 1 Times free

}

Autoptr<t>&operator= (AUTOPTR<T>&AP)

{

if (this!= &ap)

{

if (ap.ptr)

{

Deleteptr;

}

Ptr= ap.ptr;

Ap.ptr= NULL;

}

Return*this;

}

t* operator* ()

{

Return*ptr;

}

t* operator-> ()

{

Returnptr;

}

Voidget_ptr ()

{

Returnptr;

}

~autoptr ()

{

if (PTR)

{

Deleteptr;

Ptr= NULL;

}

}

Private

T*ptr;

};

Voidfuntest ()

{

int*p = new int (1);

AUTOPTR<INT>AP1 (P); I just tuned the constructor, not the copy constructor.

AUTOPTR<INT>AP2 (AP1)//Tuned copy constructor, Ap1=null;

autoptr<int>ap3;

Ap3= ap2;//assignment is not over, because the two object address is different, ap2.ptr is not empty, so call the Operator= function, but now has released

//AP3 's ptr-pointing space, so you can't assign values to AP3

int main ()

{

Funtest ();

System ("pause");

Return0;

}

the realization of unique_ptr

Template<classt>

Class Unique_ptr//predecessor is SCOPED_PT, to achieve rough-> prohibit transfer--> exclusive resources (only one pointer is allowed to manage resources)

(Disables the transfer of copy constructs and assignment operators), it can only manage a single object

{

Public

Unique_ptr (T*p =null)

:p TR (P)

{}

t* operator* ()

{

Return*ptr;

}

t* operator-> ()

{

Returnptr;

}

Voidget_ptr ()

{

Returnptr;

}

~ unique_ptr ()

{

if (PTR)

{

Deleteptr;

Ptr= NULL;

}

}

Private

Unique_ptr (unique_ptr <t>&ap);//Prohibit copy construction

Unique_ptr <t>&operator= (unique_ptr <t>&ap1)//Prohibit assignment

T*ptr;

};

Why unique_ptr the implementation of the anti-copy must be a private declaration.

1, only to the common Declaration, do not give the definition. (The user can redefine the definition outside the class)

2, only the definition of private (but within the class can be adjusted copy construction and assignment operators)

So the proprietary declaration copy constructor and the assignment operator overload function are used to implement UNIQUE_PTR's anti-copy

the realization of shared_ptr

Template<classt>

Class Share_ptr

{

Public

Share_ptr (T*p =null)

: _p (P)

, _pcount (NULL)

{

if (NULL!= _p)

{

_pcount= new int (1);//Construction succeeds with an object initialized to 1

}

}

Share_ptr (const SHARE_PTR<T>&PS)

: _p (ps._p)

, _pcount (Ps._pcount)

{

if (NULL!= _pcount)

{

++*_pcount;

}

}

t* operator* ()

{

return*_p;

}

t* operator-> ()

{

Return_p;

}

Voidget_ptr ()

{

Return_p;

}

~share_ptr ()

{

if (null!=_pcount&&0 ==* (--_pcount))

{

Delete_pcount;

_pcount= NULL;

delete_p;

_p= NULL;

}

}

Private

t* _p;

Int*_pcount;

};

Voidfuntest ()

{

SHARE_PTR<INT>PS1 (Newint);//ps1->_pcount=1;

SHARE_PTR<INT>PS2 (PS1);//ps2->_pcount=2;

share_ptr<int>ps3;

ps3= ps2;//ps3->_pcount=2;

}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.