Search code examples
c++pointerssmart-pointersunique-ptr

How to assign value to the unique_ptr after declaring it?


#include <iostream>
#include <memory> // unique_ptr

using namespace std;

int main()
{
    std::unique_ptr<char*> char_ptr;

    char_ptr = (char*)"anisha";
    return 0;
}

I want to assign some value to that unique_ptr elsewhere in the code.
This gives the following error: char_ptr = (char*)"anisha";

error: no match for ‘operator=’ (operand types are ‘std::unique_ptr<char*>’ and ‘char*’)
     char_ptr = (char*)"anisha";

How to assign value to the unique_ptr after declaring it?


Solution

  • Use std::make_unique. Here is edit to your code -

    #include <iostream>
    #include <memory> // unique_ptr
    
    using namespace std;
    
    int main()
    {
        std::unique_ptr<char*> char_ptr;
    
        //char_ptr = (char*)"anisha";
        char_ptr = std::make_unique<char*>((char*)"anisha");
        return 0;
    }