Search code examples
c++unique-ptrnullptr

C++ initialize a unique_ptr with int 0 problem


environment: C++11/14 and MacOS Clion

First, I know it is better to construct a unique_ptr with nullptr rather than with int: 0, but I just wonder what causes the following two compilation results:

// compile just fine
class MyClass {};

void MyFunc(unique_ptr<MyClass>) {

}

int main() {
    MyFunc(0);
    return 0;
}
// compile error
class MyClass {};

void MyFunc(unique_ptr<MyClass>) {

}

int main() {
    MyFunc(int(0));
    return 0;
}

the latter one with error:

note: candidate function not viable: no known conversion from 'int' to 'unique_ptr' for 1st argument

After examining unique_ptr's constructor, I find the following a canditate:

constexpr unique_ptr( nullptr_t ) noexcept;

So I try further:

// good
int main() {
    nullptr_t mynullptr(0);
    return 0;
}

on the other hand:

// error
int main() {
    nullptr_t mynullptr(int(0));
    return 0;
}

with message:

error: cannot initialize a variable of type 'std::nullptr_t' (aka 'nullptr_t') with an rvalue of type 'int'

nullptr_t mynullptr(int(0));

So is it because the initialization of nullptr that leads to the compile error?


Solution

  • Credit on the comment of M.M:

    literal 0 may be converted to nullptr ; other integer expressions may not (even if they are constant and have value zero)