Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

should assign `nullptr` to `std::unique_ptr` before assigning a new value to it?

Tags:

c++

#include <iostream>
#include <memory>
using namespace std;

int main() {
    std::unique_ptr<int> ptrA = std::make_unique<int>(10);

    ptrA = std::make_unique<int>(20); // case I

    return 0;
}


#include <iostream>
#include <memory>
using namespace std;

int main() {
    std::unique_ptr<int> ptrA = std::make_unique<int>(10);

    ptrA = nullptr;                  // case II or ptrA.reset()
    ptrA = std::make_unique<int>(20);

    return 0;
}

I have seen many people use Case II. However, std::unique_ptr is a smart pointer, I don't think we should assign either nullptr or call reset before reassigning a new value to it.

Please correct me if I am wrong here.

like image 794
q0987 Avatar asked Jun 16 '16 19:06

q0987


1 Answers

Assigning nullptr before assigning a new value is pointless.

like image 123
Jesper Juhl Avatar answered Nov 15 '22 00:11

Jesper Juhl