Alex F
Alex F

Reputation: 43331

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>'

Upvotes: 3

Views: 896

Answers (2)

Andy Prowl
Andy Prowl

Reputation: 126522

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;
//          ^^^^^^^            
}

Upvotes: 10

hmjd
hmjd

Reputation: 122001

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;
    }
}

Upvotes: 1

Related Questions