智能指针和多态性
我实现了引用计数指针(在示例中称为 SP
),但我遇到了多态性问题,我认为我不应该这样做。
在以下代码中:
SP<BaseClass> foo()
{
// Some logic...
SP<DerivedClass> retPtr = new DerivedClass();
return retPtr;
}
DerivedClass
继承自BaseClass
。对于普通指针,这应该可以工作,但是对于智能指针,它会显示 “无法从 'SP
,我认为它指的是智能指针的复制构造函数。
如何允许这种带有引用计数指针的多态性? 我很感激代码示例,因为如果我遇到这个问题,显然我在这里做错了什么。
PS:请不要告诉我使用带有智能指针的标准库,因为目前这是不可能的。
I implemented reference counting pointers (called SP
in the example) and I'm having problems with polymorphism which I think I shouldn't have.
In the following code:
SP<BaseClass> foo()
{
// Some logic...
SP<DerivedClass> retPtr = new DerivedClass();
return retPtr;
}
DerivedClass
inherits from BaseClass
. With normal pointers this should have worked, but with the smart pointers it says "cannot convert from 'SP<T>' to 'const SP<T>&"
and I think it refers to the copy constructor of the smart pointer.
How do I allow this kind of polymorphism with reference counting pointer?
I'd appreciate code samples cause obviously im doing something wrong here if I'm having this problem.
PS: Please don't tell me to use standard library with smart pointers because that's impossible at this moment.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
相当明显:
应该是:
Fairly obvious:
should be:
您应该为
SP
添加隐式转换构造函数:You should add implicit converting constructor for
SP<T>
:为什么不添加一个模板赋值运算符:(
也许还有复制构造函数)?
Why not add a template assignment operator:
(and maybe copy constructor, too)?
除了复制构造函数之外:
您还需要一个转换构造函数:
否则,编译器将不知道如何从
SP
构造SP
;对他来说,它们是无关的。转换构造函数相当简单,因为在内部您可以自动将
*DerivedClass
转换为*BaseClass
。代码可能与复制构造函数的代码非常相似。In addition to the copy constructor:
you need a conversion constructor:
Otherwise, the compiler will not know how to construct
SP<BaseClass>
from aSP<DerivedClass>
; for him, they are unrelated.The conversion constructor is fairly trivial, since internally you can convert
*DerivedClass
to*BaseClass
automatically. Code may be very similar to that for the copy constructor.