0

ラムダをカスタム デリーターとして使用できますか。実際、私は C++ ライブラリを使用しています。このライブラリでは、多くのクラスがインスタンス ライフ管理のために作成/リリース API を使用しています (以下の例を参照)。

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

したがって、その種のクラスを使用するには、自分で処理する必要がありますrelease(リターン、スローなどで)。

FileInterface* pFile = nullptr;
int ret = RealFile::createFileInterface("test.bin", pFile);
std::cout << "isValid = " << pFile->isValid() << std::endl;
pFile->release();

したがって、スマート ポインターを使用して、作成/解放ロジックを処理します。私の最初のステップは、デリータに対処することでしたが、うまくいきました

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;

しかし、作成ロジックのラムダを書いた2番目のステップで:

auto smartAllocator = [](const std::string& filename){
    FileInterface* pFile = nullptr;
    int ret = RealFile::createFileInterface(filename, pFile);
    if (ret != 0) return nullptr;
    else return pFile;
};

コンパイラ レポート エラー:

CreateReleasePattern.cpp(65): error C3487: 'FileInterface *': all return expressions in a lambda must have the same type: previously it was 'nullptr'
1>CreateReleasePattern.cpp(65): error C2440: 'return' : cannot convert from 'FileInterface *' to 'nullptr'
1>          nullptr can only be converted to pointer or handle typesCreateReleasePattern.cpp(65): error C3487: 'FileInterface *': all return expressions in a lambda must have the same type: previously it was 'nullptr'
1>CreateReleasePattern.cpp(65): error C2440: 'return' : cannot convert from 'FileInterface *' to 'nullptr'
1>          nullptr can only be converted to pointer or handle types

どうすれば修正できますか?FileInterface に記述できる変換可能な演算子はありますか?

4

1 に答える 1