Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error on implicit cast from std:unique_ptr to bool

I am using Allegro to create a simple game. When I try to validate that my pointer to the display is not null I get a compiler error telling me

error C2664: 'void validate(bool,std::string)' : cannot convert argument 1 from 'std::unique_ptr< ALLEGRO_DISPLAY,main::< lambda_996846ce92067e506da99cad36e610cf>>' to 'bool'

Here is my code

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

If I pass validate "!display" instead of "display" it works. I realize I could call validate with display.get(), but I wanted to know why it isn't working when I pass a smart pointer.

I found this bug report. I am using Visual Studio 2013. https://connect.microsoft.com/VisualStudio/feedbackdetail/view/775810/c-11-std-unique-ptr-cast-to-bool-fails-with-deleter-lambda

like image 830
janovak Avatar asked May 29 '15 05:05

janovak


People also ask

What happens when unique_ptr goes out of scope?

std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope. The object is disposed of, using the associated deleter when either of the following happens: the managing unique_ptr object is destroyed.

Can you pass unique_ptr to a function?

Why can I not pass a unique_ptr into a function? You cannot do that because unique_ptr has a move constructor but not a copy constructor. According to the standard, when a move constructor is defined but a copy constructor is not defined, the copy constructor is deleted.

What does get () do on a unique_ptr?

unique_ptr::getReturns a pointer to the managed object or nullptr if no object is owned.

Why should you use unique_ptr?

Use unique_ptr when you want to have single ownership(Exclusive) of the resource. Only one unique_ptr can point to one resource. Since there can be one unique_ptr for single resource its not possible to copy one unique_ptr to another.


1 Answers

std::unique_ptr is not implicitly convertible to bool. It is contextually convertible to bool (due to its explicit conversion operator), which is why you can use it in an if statement, or put a ! in front of it, but you cannot pass it as an argument to a function which is expecting a bool.

like image 93
Benjamin Lindley Avatar answered Oct 16 '22 15:10

Benjamin Lindley