【发布时间】:2015-04-29 17:26:27
【问题描述】:
我最近在用std的smartptrs,用“shared_ptr”写了一大堆代码,脑子里有点问题:
-
有两个类:
class base{} class drived: public base{}还有两个这样的功能:
void fconst(const shared_ptr<classA>& obj){} void f(shared_ptr<classA>& obj){}
这个函数用于调用测试:
void test()
{
std::shared_ptr<drived> obj(std::make_shared<drived>());
f(obj); // this is error in vc++, because type is not compatibility
fconst(obj); // this is ok in vc++
}
我知道f 调用是错误的,但为什么fconst 调用正常?
如果使用base*有一个好处:当函数接收到base*作为参数时,调用者可以将所有base的孩子作为参数。
当使用shared_ptr时,有没有类似的字符?
fconst 测试调用的行为是一个可靠的标准吗?
2。
当shared_ptr传入函数参数时,这些用法的时候:
void f(const shaerd_ptr<classA> obj)
void f(const shaerd_ptr<classA>& obj)
void f(shaerd_ptr<classA> obj)
void f(shaerd_ptr<classA>& obj)
感谢您的帮助!
编辑: 谢谢~,我也有以下代码的问题:
无效测试()
{
std::shared_ptr obj(std::make_shared());
f(obj); // 这是vc++中的错误,因为类型不兼容
fconst(obj); // 这在 vc++ 中是可以的
// 继续..
std::shared_ptr<base> objBase(std::make_shared<base>());
f(objBase); // this is ok, why?
fconst(objBase); // this is ok after your answer
}
【问题讨论】:
-
您不能将非 const 引用绑定到临时引用,但可以绑定 const 引用。
-
我已经更新了我的问题,请再次帮忙,谢谢!~~
标签: c++ c++11 parameters shared-ptr