简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM