Search code examples
c++initializationc++14smart-pointersunique-ptr

Is there a more concise way to initialize a unique_ptr<char[]> than this?


So at the moment I have:

std::string a;
std::unique_ptr<char[]> b(std::make_unique<char[]>(a.size() + 1));
std::copy(std::begin(a), std::end(a), b.get());

Is it is possible to initialize this directly in one step?


Solution

  • Is it is possible to initialize this directly in one step?

    I would suggest keeping it as std::string or std::vector<char>.

    However, if you really insist, Yes! Using an immediately invoking a lambda, this can be done.

    std::unique_ptr<char[]> b = [&a]() {
       auto temp(std::make_unique<char[]>(a.size() + 1));
       std::copy(std::begin(a), std::end(a), temp.get());
       return temp;
    }(); // invoke the lambda here!
    

    The temp will be move constructed to the b.

    (See a Demo)


    If the string a will not be used later, you could move it to the std::unique_ptr<char[]>, using std::make_move_iterator.

    #include <iterator>  // std::make_move_iterator
    
    std::unique_ptr<char[]> b(std::make_unique<char[]>(a.size() + 1));
    std::copy(std::make_move_iterator(std::begin(a)),
       std::make_move_iterator(std::end(a)), b.get());
    

    If that needs to be in one step, pack it to the lambda like above.