问题描述
我想做的是,允许使用setter函数传递指针,引用或常量引用:
What I am trying to do is, allow a pointer, reference or constant reference to be passed with the setter function:
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)
会调用setS()
函数的const std::string&
版本.
But I have seen that, if the pointer version is not there, the setS(0)
calls the const std::string&
version of the setS()
function.
在指针和参考版本之间或在其他重要内容之间是否存在歧义?是否定义明确,并希望它在所有编译器中均以相同的方式工作?
Is there any ambiguity between the pointer and the reference versions or among any others that matter? Is it well defined and expected to work the same way in all compilers?
推荐答案
没有歧义.当您在重载集中包含A& setS(std::string* s)
时,setS(0)
会调用指针版本,而0
是空指针.等同于setS(nullptr)
.
There is no ambiguity. When you have A& setS(std::string* s)
in the overload set then setS(0)
calls the pointer version and 0
is a null pointer. It would be the equivelent of setS(nullptr)
.
当A& setS(std::string* s)
不在重载集中时,编译器将查看是否有一种方法可以从0
构造一个临时字符串,然后将其传递给A& setS(const std::string& s)
,因为const&
可以绑定到一个临时的. std::string
可以由单个指针构造,而0
可以再次作为空指针.因此,您将获得一个构造为std::string
的临时空指针,该指针将传递给const&
函数.
When A& setS(std::string* s)
is not in the overload set then the compiler looks to see if there is a way it can construct a temporary string from 0
and then pass that to A& setS(const std::string& s)
since a const&
can bind to a temporary. std::string
can be constructed from a single pointer and again 0
it tread as a null pointer. So you get a temporary null pointer constructed std::string
passed to the const&
function.
这是未定义的行为. std::string
的构造函数要求传递给它的指针是一个以null终止的c字符串.如果不是,则行为是不确定的.
This is undefined behavior though. The constructor for std::string
requires that the pointer passed to it be a null terminated c string. If it is not then the behavior is undefined.
这篇关于具有指针,引用和常量引用参数的函数调用歧义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!