我正在使用 Allegro 创建一个简单的游戏。当我尝试验证指向显示器的指针不为空时,我收到编译器错误提示
error C2664: 'void validate(bool,std::string)' : cannot convert argument 1 from 'std::unique_ptr< ALLEGRO_DISPLAY,main::< lambda_996846ce92067e506da99cad36e610cf>>' to 'bool'
这是我的代码
#include <iostream>
#include <memory>
#include <string>
#include <allegro5\allegro.h>
using namespace std;
const int WIDTH = 512;
const int HEIGHT = 512;
void validate(bool ptr, string errorMessage) {
if (!ptr) {
cerr << errorMessage << endl;
exit(-1);
}
}
int main() {
auto deleter = [](ALLEGRO_DISPLAY* d) { al_destroy_display(d); };
unique_ptr<ALLEGRO_DISPLAY, decltype(deleter)> display;
validate(al_init(), "Failed to initialize Allegro");
display = unique_ptr<ALLEGRO_DISPLAY, decltype(deleter)>(al_create_display(WIDTH, HEIGHT), deleter);
validate(display, "Failed to create display");
return 0;
}
如果我通过验证“!display”而不是“display”,它就可以工作。我意识到我可以用 display.get() 调用验证,但我想知道为什么当我传递智能指针时它不起作用。
我找到了这个错误报告。我正在使用 Visual Studio 2013。 https://connect.microsoft.com/VisualStudio/feedbackdetail/view/775810/c-11-std-unique-ptr-cast-to-bool-fails-with-deleter-lambda
最佳答案
std::unique_ptr
不能隐式转换为 bool。它可以根据上下文转换为 bool(由于它的 explicit conversion operator ),这就是为什么你可以在 if 语句中使用它,或者在它前面放一个 !
,但你不能将它作为一个传递一个期望 bool 的函数的参数。
关于c++ - 来自 std :unique_ptr to bool 的隐式转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30521849/