This example compiles and runs well with gcc 4.8.3:
#include <memory> #include <functional> #include <iostream> int main() { auto str = new const char[6]{'h', 'e', 'l', 'l', 'o', '\0'}; std::unique_ptr<const char[], std::function<void(const char *)>> u_ptr(str, [](const char *s){ delete[] s; }); std::cout << u_ptr.get() << std::endl; } But when I try it with Visual Studio Professional 2013 it doesn't compile (complains about a deleted function). Is this not yet possible with Visual Studio 2013? Or is my sample code wrong and gcc ignores my mistake?
Error is:
main.cpp(8) : error C2280: 'std::unique_ptr>::unique_ptr>(_Ptr2,_Dx2)' : attempting to reference a deleted function with [ _Ptr2=const char * , _Dx2=main:: ] C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\INCLUDE\memory(16 16) : see declaration of 'std::unique_ptr>::unique_ptr'
std::functionas aunique_ptrdeleter a terrible idea?"Tbecharinstead ofchar const[]? This works on Visual C++ 2015 RC.std::unique_ptralready supportsdelete[]there is no reason to write your own here.unique_ptrrequires that all operations associated with its deleter must not throw;std::function's constructors can throw, because it uses type erasure and may need to allocate memory under the hood. (In the OP's code it's even worse, because thestd::functionwould be constructed beforeunique_ptr's constructor is called, and if that throws then the pointer is leaked regardless of whatunique_ptrrequires.)