c++ - Can we create unique_ptr using a lambda? -
can use lambda custom deleter. in fact, use c++ library in lot of class use create/release api instance life management (see example below)
class fileinterface { public: virtual ~fileinterface() {} virtual bool isvalid() = 0 ; virtual void release() = 0; }; class realfile : public fileinterface { public: static int createfileinterface(const std::string& filename, fileinterface*& pfileinst) { try { pfileinst = new realfile(filename); } catch (...){ return -1; } return 0; } virtual bool isvalid() { return (m_pfile != null);} virtual void release() { delete this;} protected: realfile(const std::string& filename) : m_pfile(null) { m_pfile = fopen(filename.c_str(), "wb"); if(m_pfile == null) {throw std::runtime_error("error while opening file.");} } ~realfile() { std::cout << "dtor" << std::endl; fclose(m_pfile); } private: file* m_pfile; };
so use kind of class need handle myself release
(at each return, throw etc... ).
fileinterface* pfile = nullptr; int ret = realfile::createfileinterface("test.bin", pfile); std::cout << "isvalid = " << pfile->isvalid() << std::endl; pfile->release();
so use smart pointer handle create/release logic. 1st step deal deleter , it's work fine
auto smartdeleter = [](fileinterface* ptr){ptr->release();}; fileinterface* pfile = nullptr; int ret = realfile::createfileinterface("test.bin", pfile); std::unique_ptr<fileinterface, decltype(smartdeleter)> smartfile(pfile); std::cout << "isvalid = " << smartfile->isvalid() << std::endl;
but in 2nd step wrote lambda create logic:
auto smartallocator = [](const std::string& filename){ fileinterface* pfile = nullptr; int ret = realfile::createfileinterface(filename, pfile); if (ret != 0) return nullptr; else return pfile; };
compiler report errors:
createreleasepattern.cpp(65): error c3487: 'fileinterface *': return expressions in lambda must have same type: 'nullptr' 1>createreleasepattern.cpp(65): error c2440: 'return' : cannot convert 'fileinterface *' 'nullptr' 1> nullptr can converted pointer or handle typescreatereleasepattern.cpp(65): error c3487: 'fileinterface *': return expressions in lambda must have same type: 'nullptr' 1>createreleasepattern.cpp(65): error c2440: 'return' : cannot convert 'fileinterface *' 'nullptr' 1> nullptr can converted pointer or handle types
how can fix ? there convertible operator write on fileinterface ?
a lambda must specify return type unless consists of single return
statement. in future, these rules might relaxed allow multiple return
statements; then, have same type, function's return type unambiguous. function returns either nullptr_t
or fileinterface*
depending on return
statement reached.
lambda syntax allows trailing return types, want:
[](const std::string& filename) -> fileinterface* { // code here }
Comments
Post a Comment