Is unique_ptr constructor initializes the raw pointer and also unique_ptr Destructor deletes the associated raw pointer?

  • Thread starter Thread starter bhavya internship
  • Start date Start date
B

bhavya internship

Guest
Hello All,

First time I am using smart pointers in my project. While using unique_ptr, I got some doubts regarding unique_ptr and raw pointer combination. And the way unique_ptr works internally.

Could some one please explain/answer based on my understanding as mentioned below, so that I can go ahead and use the smart pointers.

Below is the example:

class A
{
public:
void show()
{
cout<<"A::show()"<<endl;
}
};

int main()
{
unique_ptr<A> p1 (new A);

p1 -> show();

// returns the memory address of p1
cout << p1.get();

retrun 0;

}

From the above example,

1. When creating unique_ptr object "p1" we are providing raw pointer. Internally, unique_ptr constructor will initialize the unique_ptr with the raw pointer. Is my understanding correct?

2. As per the unique_ptr definition, "The pointer is exclusively owned by one object or a resource".

Based on the above statement, in our scenario, "raw pointer" is exclusively owned by the unique_ptr object "p1". Am I correct?

3. And also after the statement, cout << p1.get(); (In the above sample program) as it is going out of scope, internally, the destructor of the unique_ptr called and it deletes the associated raw pointer. Is my understanding correct?

4. Finally, once deletes the associated raw pointer is the unique_ptr object will become empty?


Thanks in advance.

Continue reading...
 
Back
Top