Search code examples
pointersc++17unique-ptrstdstring

how to construct a unique pointer that points to a certain string


Given a string s e.g. auto s = std::string("hello"), how would you write code to make a unique pointer that points to a created copy of this string (not necessarily s) - I've tried many variations of auto ptr = std::make_unique<std::string>(s) but nothings seems to be working.


Solution

  • This works just fine for me:

        std::string s = "ABCDE";
        auto ptr = std::make_unique<std::string>(s);
        std::cout << s << std::endl;
        std::cout << *ptr << std::endl;
        s = "UVWXYZ";
        std::cout << s << std::endl;
        std::cout << *ptr << std::endl;
    

    gives me output:

    ABCDE
    ABCDE
    UVWXYZ
    ABCDE
    

    is that what you're trying to accomplish?