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
What are special characters c++?
How do you save a c++ program?
What is the type of 'this' pointer?
Explain the benefits of proper inheritance.
What are files in c++?
Which programming language is best?
Differences between private, protected and public and give examples.
What are the manipulators in c++?
Is there any difference between int [] a and int a [] in c++?
What is the auto keyword good for in c++?
Is c++ pass by reference or value?
What is the use of class in c++?
If dog is a friend of boy, is boy a friend of dog?
How do you differentiate between overloading the prefix and postfix increments?
What is the difference between structures and unions?