假设我有一个克隆派生类的基类:
class Base
{
public:
virtual Base * clone()
{
return new Base();
}
// ...
};
Run Code Online (Sandbox Code Playgroud)
我有一组派生类,使用奇怪的重复模板模式实现:
template <class T>
class CRTP : public Base
{
public:
virtual T * clone()
{
return new T();
}
// ...
};
Run Code Online (Sandbox Code Playgroud)
我试图从这个进一步得出这样的:
class Derived : public CRTP<Derived>
{
public:
// ...
};
Run Code Online (Sandbox Code Playgroud)
我得到编译错误的效果:
error C2555: 'CRTP<T>::clone': overriding virtual function return type differs and is not covariant from 'Base::clone'
Run Code Online (Sandbox Code Playgroud)
我意识到这可能是编译器在实例化CRTP时不完全知道Derived的继承树的结果.此外,用(Base*)替换返回类型(T*)也会编译.但是,我想知道是否存在保留上述语义的工作.
c++ templates visual-studio-2010 crtp f-bounded-polymorphism
我有一个对象层次结构,需要能够从基类克隆对象.我遵循了典型的CRTP模式,除了我还希望能够在孩子直接调用复制时返回子类.为此,我遵循了这里的建议:https://stackoverflow.com/a/30252692/1180785
它似乎工作正常,但Clang警告我,我有潜在的内存泄漏.我把代码减少到了这个MCVE:
template <typename T>
class CRTP {
protected:
virtual CRTP<T> *internal_copy(void) const {
return new T(static_cast<const T&>(*this));
}
public:
T *copy(void) const {
return static_cast<T*>(internal_copy());
}
virtual ~CRTP(void) = default;
};
class Impl : public CRTP<Impl> {
};
int main(void) {
Impl a;
Impl *b = a.copy();
delete b;
}
Run Code Online (Sandbox Code Playgroud)
据我所知,那里没有可能的内存泄漏,但是通过XCode运行Clang显示了这一点:
是否有内存泄漏吗?如果不是,导致误报的原因是什么?我该如何解决?(我宁愿不关闭静态分析)