I am trying to use std::unique_ptr
with deleter. This is my code:
template<class T>
struct Deleter
{
void operator()(T* p)
{
delete[] p;
}
};
void Test()
{
vector<unique_ptr<char>> v;
for(size_t i = 0; i < 5; ++i)
{
char* p = new char[10];
sprintf(p, "string %d", i);
v.push_back( unique_ptr<char, Deleter<char>>(p) ); // error is here
}
}
error C2664: 'void std::vector<_Ty>::push_back(std::unique_ptr &&)' : cannot convert parameter 1 from 'std::unique_ptr<_Ty,_Dx>' to 'std::unique_ptr<_Ty> &&'
Compiler: VC++ 2012. How can I fix this? My goal is to use unique_ptr
with custom deleter which calls delete[]
instead of default delete
.
There's no need, since unique_ptr
knows about arrays already!
std::unique_ptr<char[]> p(new char[10]);
sprintf(p.get(), "...");
The array specialization even gives you array-like access à la p[0] = 'a';
etc.
Your vector type has to match, of course: std:vector<std::unique_ptr<char[]>>
unique_ptr<char>
and unique_ptr<char, Deleter<char>>
are two different types. Therefore, you should declare your vector as:
vector<unique_ptr<char, Deleter<char>>> v;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.