注册 登录
编程论坛 C++教室

shared_ptr构找函数问题

韩海0312 发布于 2017-06-23 23:29, 1869 次点击
程序代码:
template<typename Tp> class shared_ptr {
public:
    template<typename _Tp1>
    explicit shared_ptr(_Tp1* __p)     //(b)  // 这里为什么是模板函数
        : __shared_ptr<_Tp>(__p) { }
};

//下面的写法不行么
template<typename Tp> class shared_ptr {
public:
    explicit shared_ptr(_Tp* __p)     //(a)   这样不行么
        : __shared_ptr<_Tp>(__p) { }
};

在处理动态绑定问题时
class B {};

class D : public B {};

shared_ptr<B> sp(new D()); //会调用对应的模板构找函数, 但是为什么是模板函数呢, (a) 就可以实现功能啊
这里有什么优缺点么?
2 回复
#2
rjsp2017-06-26 08:29
因为它想知道 _Tp1 是不是继承自 std::enable_shared_from_this
如果转化基类的话,那它就没法知道了。

程序代码:
#include <memory>

struct A
{
};
struct B : A, std::enable_shared_from_this<B>
{
};

int main( void )
{
    std::shared_ptr<A>( new B );
}

#3
韩海03122017-06-26 19:25
回复 2楼 rjsp
牛叉
1