为什么{}按顺序转换为std :: nullptr_t?

时间:2017-09-06 18:46:07

标签: c++ c++14

此代码:

#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)

为什么operator=选择了std::nullptr_t

1 个答案:

答案 0 :(得分:18)

我们有三位候选人:

  1. select ID , UserID , CreatedDate , [Status] from TableA A inner join ( select max(CreatedDated) [MaxDate] , UserID , [Status] from TableA where [Status] = 0 group by UserID, [Status] ) B on A.UserID = B.UserID and A.CreatedDate = B.MaxDate and A.[Status] = B.[Status]
  2. operator=(T const& )
  3. operator=(std::vector<int> const& )
  4. 对于#1和#2,operator=(std::nullptr_t )会导致user-defined conversion sequence

    但是,对于#3,{}standard conversion sequence,因为{}不是类类型。

    由于标准转换序列是better than用户定义的转换序列,#3获胜。