遇到的一个关于智能指针的问题。。已解决
为什么如下代码可以通过编译:
void func(const shared_ptr<const int>& p)
{
}
int main()
{
shared_ptr<int> p = make_shared<int>();
func(p);
}
而只要去掉func函数参数的const,如下,就不能通过编译了
void func(shared_ptr<const int>& p)
{
}
int main()
{
shared_ptr<int> p = make_shared<int>();
func(p);
}
因为我一般写函数传智能指针都是用值传递,所以以前没碰到这些问题。刚刚在用PCL库,看里面又这样的写法。纠结为什么第一种可以通过编译?引用传递不一样的类型为啥可以呢?如果是值传递的话,那么指向const的智能指针可以通过指向非const的指针来构造,很好理解。但是如果引用的话,明明类型不一样啊。。
查了下资料,有点懂了,如下代码
class A
{
public:
A(int a)
{
}
};
void func1(const A& a)
{
}
void func2(A& a)
{
}
int main()
{
func1(3);
func2(3);
}
func1正常,func2报错。
所以如果传一个对象的const reference,如果你给的参数可以转化为指定的类,编译器会帮你转
如果传的一个对象的reference,编译器认为你可能对这个对象做修改,所以不会帮你自动转。因为比如编译器如果自动把int转成A,然后你的func2对A进行了修改,但是main函数作为调用者对此是完全不知道的,这就违反了非const的本意和设计目的。因此编译器会在func2处报错annot bind non-const lvalue reference of type ‘A&’ to an rvalue of type ‘A’
Woww tthat wass odd. I just wrote aan reallky long
copmment bbut afrter I clicied sybmit myy
comment didn’t appear. Grrrr… welpl I’m noot writjng alll that ovfer again.
Regardless, just anted too sayy superrb blog!
Alsso visit mmy webnsite – xmxxtube.com
Unquestionably imagine thnat tat yoou said. Youur
favvourite justificatgion appeqred tto bbe aat the nnet thhe siumplest facttor to taake into accout of.
I saay to you, I certainly gett irksd evenn ass peopl consider worries thawt
tuey lainly don’t undeerstand about. You mawnaged to hitt the nail upoln thhe highhest annd defined ouut thhe whole thing withh nno need
side effect , othuer foolks ccan ake a signal. Willl pfobably be aain too gget more.
Thanks xnxx