jeudi 30 novembre 2017

Initialize with nullptr

When initializing with a pointer a nullptr can be ambiguous if there are multiple constructors accepting a pointer argument.
You can solve this by casting C cast or static_cast, example:

#include <iostream>
#include <cstddef>

using namespace std;

struct A{
    A(int*){ cout << "int constructor" << endl;}
    A(double*) { cout << "double constructor" << endl;}
};

struct B{
    B(std::nullptr_t) { cout << "nullptr constructor" << endl;}
    B(int*){ cout << "int constructor" << endl;}
    B(double*) { cout << "double constructor" << endl;}
};

int main(){
    //A a(nullptr); constructor is ambiguous 
    A a1((int*)nullptr);// int constructor
    A a2(static_cast<double*>(nullptr));// double constructor

    B b(nullptr);// nullptr constructor
    return 0;
}

I included B to illustrate that a constructor with std::nullptr_t exist and is possible but for this question let's focus on A.

From "Why use static_cast(x) instead of (int)x?" I understand the most dangerous thing about C cast being you don't know which will be used:

The main reason is that classic C casts make no distinction between what we call static_cast<>(), reinterpret_cast<>(), const_cast<>(), and dynamic_cast<>(). These four things are completely different.

Are any of these casts unsafe for a nullptr or can you safely use the C-style cast?

Aucun commentaire:

Enregistrer un commentaire