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

Question

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

Answers 1
Added at 2017-09-06 20:09
Tags
Question

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?

Answers to

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

nr: #1 dodano: 2017-09-06 21:09

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.

Source Show
◀ Wstecz