Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why {} converted to std::nullptr_t in first order?

Tags:

This code:

#include <iostream>
#include <vector>

using namespace std;

void dump(const std::string& s) {
    cout << s << endl;
}

class T {
public:
    T() {
        dump("default ctor");
    }

    T(std::nullptr_t) {
        dump("ctor from nullptr_t");
    }

    T(const T&) {
        dump("copy ctor");
    }

    T& operator=(const T&) {
        dump("copy operator=");
        return *this;
    }

    T& operator=(std::nullptr_t) {
        dump("operator=(std::nullptr_t)");
        return *this;
    }

    T& operator=(const std::vector<int>&) {
        dump("operator=(vector)");
        return *this;
    }
};

int main() {
    T t0;

    t0 = {};

    return 0;
}

outputs:

default ctor
operator=(std::nullptr_t)

why operator= with std::nullptr_t was selected?

like image 370
vladon Avatar asked Sep 06 '17 18:09

vladon


Video Answer


1 Answers

We have three candidates:

  1. operator=(T const& )
  2. operator=(std::vector<int> const& )
  3. operator=(std::nullptr_t )

For both #1 and #2, {} leads to a user-defined conversion sequence.

However, for #3, {} is a standard conversion sequence because nullptr_t is not a class type.

Since a standard conversion sequence is better than a user-defined conversion sequence, #3 wins.

like image 180
Barry Avatar answered Sep 30 '22 03:09

Barry