向量构造函数中的函数匹配

Function matching in vector constructors

本文关键字:函数 构造函数 向量      更新时间:2023-10-16
#include <string>
#include <iostream>
#include <vector>
class HasPtrValue {
public:
    HasPtrValue(const HasPtrValue& h): ps(new std::string(*h.ps)) { std::cout << "copy" << std::endl;}
    HasPtrValue(const std::string &s = std::string()): ps(new std::string(s)) { std::cout << "string/default" << std::endl;}
    ~HasPtrValue() { delete ps; }
private:
    std::string *ps;
};
using namespace std;
int main(){
    string s = "stackoverflow";
    vector<HasPtrValue> a(5, s);
}

上面的代码编译了精细的输出:

string/default
copy
copy
copy
copy
copy

这对我来说意味着向量首先使用字符串对象直接初始化一个临时的 HasPtrValue 对象(执行 HasPtrValue(,然后从这个临时对象复制构造 5 个元素。那么,为什么下面的代码不能编译:

int main(){
    vector<HasPtrValue> a(5, "stackoverflow");
}

如果它直接初始化 HasPtrValue(执行 HasPtrValue("stackoverflow"((,那么 const string&constructor 承担创建临时角色就不会有问题。我收到错误;

 error: no matching function for call to 'std::vector<HasPtrValue>::vector(int, const char [14])'|

我想我会尝试使用一个更简单的类,该类使用 int 构造函数并从双精度转换:

class A{
public:
    A(const int& a): x(a) { }
    int x = 2;
};
int main(){
    vector<A> a(5, 5.5);
}

除了这个编译正常。矢量实现的哪一部分阻止在构造函数中使用 const char* 转换?

因为它需要两个用户定义的转换,const char* -> std::string ,然后std::string -> HasPtrValue ,但在隐式转换序列中只允许一次用户定义的隐式转换。

13.3.3.1.2$1 用户自定义转换序列 [over.ics.user]

用户定义的转换序列由初始标准组成 转换序列后跟用户定义的转换 (12.3( 后跟第二个标准转换序列。

请注意,这里只有一个级别的用户定义的隐式转换是合法的。对于您的情况,这必须通过显式转换来处理;因此,您可以:

vector<HasPtrValue> a(5, std::string("stackoverflow"));
int main(){
    vector<HasPtrValue> a(5, string("stackoverflow"));
}

您的构造函数需要std::string并且"stackoverflow"char数组。或者,您可以定义接受char[]的其他构造函数。