What is a smart pointer?

Answer Posted / akhilesh kumar jaiswal

A smart pointer is an object that acts, looks and feels like a normal pointer but offers more functionality. In C++, smart pointers are implemented as template classes that encapsulate a pointer and override standard pointer operators. They have a number of advantages over regular pointers. They are guaranteed to be initialized as either null pointers or pointers to a heap object. Indirection through a null pointer is checked. No delete is ever necessary. Objects are automatically freed when the last pointer to them has gone away. One significant problem with these smart pointers is that unlike regular pointers, they don't respect inheritance. Smart pointers are unattractive for polymorphic code. Given below is an example for the implementation of smart pointers.
Example:
template <class X>
class smart_pointer
{
public:
smart_pointer(); // makes a null pointer
smart_pointer(const X& x) // makes pointer to copy of x

X& operator *( );
const X& operator*( ) const;
X* operator->() const;

smart_pointer(const smart_pointer <X> &);
const smart_pointer <X> & operator =(const smart_pointer<X>&);
~smart_pointer();
private:
//...
};
This class implement a smart pointer to an object of type X. The object itself is located on the heap. Here is how to use it:
smart_pointer <employee> p= employee("Harris",1333);
Like other overloaded operators, p will behave like a regular pointer,
cout<<*p;
p->raise_salary(0.5);

Is This Answer Correct ?    0 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

How does code-bloating occur in c++?

749


Of the numbers 12 23 9 28 which would be at the top of a properly implemented maxheap a) 28 b) 9 c) Any of them could be

928


What are virtual functions in c++?

687


What is conditions when using boolean operators?

594


C is to C++ as 1 is to a) What the heck b) 2 c) 10

639






Give the difference between the type casting and automatic type conversion. Also tell a suitable C++ code to illustrate both.

630


Define stacks. Provide an example where they are useful.

575


What is the difference between while and do while loop?

556


Is map thread safe c++?

628


What is object oriented programming (oop)?

621


What is overloading unary operator?

598


What does getch() do according to the ANSI C++ standard a) Reads in a character b) Checks the keyboard buffer c) Nothing in particular (Its not defined there)

599


What happens when you make call 'delete this;'?

603


What is the difference between the indirection operator and the address of oper-ator?

606


What is binary object model?

600