C++ 我们可以使用lambda创建唯一的_ptr吗?

C++ 我们可以使用lambda创建唯一的_ptr吗?,c++,c++11,lambda,C++,C++11,Lambda,我可以使用lambda作为自定义删除器。事实上,我使用C++库,其中很多类使用创建/发布API(例如生命管理)(见下面的例子) 因此,我将使用智能指针来处理创建/发布逻辑。我的第一步是处理删除器,它的工作很好 auto smartDeleter = [](FileInterface* ptr){ptr->release();}; FileInterface* pFile = nullptr; int ret = RealFile::createFileInterface("test.bin

我可以使用lambda作为自定义删除器。事实上,我使用C++库,其中很多类使用创建/发布API(例如生命管理)(见下面的例子)

因此,我将使用智能指针来处理创建/发布逻辑。我的第一步是处理删除器,它的工作很好

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;
编译器报告错误:

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上编写的可转换运算符?

lambda必须指定其返回类型,除非它由单个
return
语句组成。将来,这些规则可能会放宽,以允许多个
return
语句;但即使这样,它们也必须是相同的类型,因此函数的返回类型是明确的。函数返回
nullptr\t
FileInterface*
,具体取决于到达哪个
return
语句

Lambda语法只允许尾部返回类型,因此您需要:

[](const std::string& filename) -> FileInterface* {
    // your code here
}

lambda必须指定其返回类型,除非它由单个
return
语句组成。将来,这些规则可能会放宽,以允许多个
return
语句;但即使这样,它们也必须是相同的类型,因此函数的返回类型是明确的。函数返回
nullptr\t
FileInterface*
,具体取决于到达哪个
return
语句

Lambda语法只允许尾部返回类型,因此您需要:

[](const std::string& filename) -> FileInterface* {
    // your code here
}

FileInterface需要一个虚拟析构函数。@NeilKirk,我同意。。。我只是在这里重写了一些代码来演示,添加虚拟dtor并不能解决这个问题。FileInterface需要一个虚拟析构函数。@NeilKirk,我同意。。。我只是在这里重写了一些代码来演示,添加虚拟dtor并不能解决这个问题。它工作得很好,我现在理解了逻辑,
nullptr\u t
可以转换到
FileInterface*
中,但必须使用该语法设置类型以解决歧义!它工作得很好,我现在理解了逻辑,
nullptr\u t
可以转换为
FileInterface*
,但必须使用该语法设置类型以解决歧义!
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
[](const std::string& filename) -> FileInterface* {
    // your code here
}