Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compilation error enumerating vector of unique_ptr

void Test()
{
    vector< unique_ptr<char[]>> v;

    for(size_t i = 0; i < 5; ++i)
    {
        char* p = new char[10];
        sprintf_s(p, 10, "string %d", i);
        v.push_back( unique_ptr<char[]>(p) );
    }

    for(auto s : v)                // error is here
    {
        cout << s << endl;
    }
}

error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>'

like image 699
Alex F Avatar asked Mar 27 '26 11:03

Alex F


2 Answers

unique_ptr is non-copyable. You should use a reference to const in your range-based for loop. Moreover, there is no overload of operator << for unique_ptr, and unique_ptr is not implicitly convertible to the underlying pointer type:

for(auto const& s : v)
//       ^^^^^^
{
    cout << s.get() << endl;
//          ^^^^^^^            
}
like image 109
Andy Prowl Avatar answered Mar 30 '26 00:03

Andy Prowl


As pointed out by Andy Prowl unique_ptr is not copyable (from the linked reference page):

unique_ptr is neither copyable nor copy-assignable

The code could avoid using unique_ptr completely and just use std::string with std::to_string() instead:

void Test()
{
    std::vector< std::string > v;

    for(size_t i = 0; i < 5; ++i)
    {
        v.push_back( std::string("string ") + std::to_string(i) );
    }

    for(auto& s : v)
    {
        std::cout << s << std::endl;
    }
}
like image 25
hmjd Avatar answered Mar 30 '26 00:03

hmjd