简体   繁体   中英

Will there be memory leak in unique_ptr here

#include<iostream>
#include<memory>
using namespace std;
int main()
{
   unique_ptr<int> p(new int);
   *p = 10;
   cout<<*p<<endl;
   p = NULL;
   if(p)
     cout<<"It's NOT NULL\n";
   else
     cout<<"It's NULL NOW\n";
   return 0;
}

// As I assigned NULL to p , when the program finishes , it will delete p which //has NULL . Though deleting NULL won't cause any issue but the memory hold by p //earlier won't get freed . Am I correct .

There will be no memory leak, although you should use p = nullptr rather than p = NULL . This is because std::unique_ptr overloads the assignment operator for the nullptr_t type:

From the standard, the effect of

unique_ptr& operator=(nullptr_t) noexcept;

is to call reset() . And that, in turn, frees any pointed-to memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM