How to use make_unique with move in C++

1 Answer

0 votes
#include <iostream>
#include <memory> // make_unique

class A
{
public:
    std::string str;
    
    A(std::string _str) {
        str = _str;
        std::cout << str << "\n";
    }
    ~A() {
        std::cout << "~A() " << str << "\n";
    }
};

int main()
{
    auto ptrA = std::make_unique<A>("aaa");
    auto ptrB = std::make_unique<A>("bbb");
    
    if (ptrA) {
        std::cout << "ptrA is not nullptr\n";
    }

    ptrB = std::move(ptrA); // after this line ptr1 holds nullptr
    
    if (!ptrA) {
        std::cout << "ptrA is nullptr\n";
    }
}



/*
run:

aaa
bbb
ptrA is not nullptr
~A() bbb
ptrA is nullptr
~A() aaa

*/

 



answered Oct 17, 2024 by avibootz
...