我想做的是,允许使用 setter 函数传递指针、引用或常量引用:
class A{
std::string * p;
std::string st;
public:
A():p(0)
{}
A& setS(const std::string& s){
std::cout<<"called with const std::string&\n";
st = s;
p = &st;
return *this;
}
A& setS(std::string& s) {
std::cout<<"called with std::string&\n";
p = &s;
return *this;
}
A& setS(std::string* s) {
std::cout<<"called with std::string*\n";
p = s;
return *this;
}
};
int main(){
std::string s;
A a;
a.setS(std::move(s)) //const std::string&
.setS("") //const std::string&
.setS(s) //std::string&
.setS(0); //std::string*
//if std::string* version is not defined,
//setS(0) calls the const std::string& version and throws exception
return 0;
}
但我已经看到,如果指针版本不存在,setS(0)
称为const std::string&
的版本setS()
功能。
指针和参考版本之间或其他重要版本之间是否存在歧义?它是否定义良好并期望在所有编译器中以相同的方式工作?
没有任何歧义。当你有A& setS(std::string* s)
然后在过载集中setS(0)
调用指针版本并0
是一个空指针。这相当于setS(nullptr)
.
When A& setS(std::string* s)
不在重载集中,那么编译器会查看是否有办法可以从中构造临时字符串0
然后将其传递给A& setS(const std::string& s)
自从一个const&
可以绑定到临时的。std::string
可以从单个指针构造并再次构造0
它作为空指针运行。所以你得到了一个临时的空指针构造std::string
传递给const&
功能。
但这是未定义的行为。构造函数为std::string
要求传递给它的指针是一个以 null 结尾的 c 字符串。如果不是,则行为未定义。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)