doubt with scope of smart pointers

I am not sure when a piece of memory a referred by a smart pointer a_sp is freed. Is it freed after a_sp being used the last time or at the end of the function where a_sp is declared? Thank you!
lantianmanAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
AxterConnect With a Mentor Commented:
Correction:

void function()
{
  for( int i = 0;i < 123;++i)
 {
       MySmartPtrType foofoo;
  }//foofoo gets free here because it goes out of scope before reaching the end of the function.

 //..some code here
}

In above example, foofoo goes out of scope, and therefor gets free over and over again, before reaching the end of the function.
So foofoo would get created and freed 123 times before the loop ends.
0
 
ikeworkCommented:
what kind of smart-pointers are you using, an own class?
0
 
AxterCommented:
>>at the end of the function where a_sp is declared?

It's free when the variable goes out of scope.
So in most cases, it would be free when the function ends.

Continue...
0
 
AxterCommented:
Example:

void function()
{
   MySmartPtrType foofoo;
  //..some code here

}//foofoo gets free here

However, if your smart pointer is inside a sub section of your function, then it would get freed when the sub section ends.

Example

void function()
{
  for( int i = 0;i < 123;++i)
  {
        MySmartPtrType foofoo;
   }
    //foofoo gets free here because it goes out of scope before reaching the end of the function.

  //..some code here
}
0
 
lantianmanAuthor Commented:
Thank you!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.