根据我之前的问题,我希望 aboost::shared_ptr<A>
实际上是A
(或可能A*
)的子类,以便它可以用于A*
作为参数的方法中。
考虑以下类:
class A
{
public:
A(int x) {mX = x;}
virtual void setX(int x) {mX = x;}
virtual int getX() const {return mX;}
private:
int mX;
};
在上一个问题中,我建议创建一个 SharedA 对象来处理这个问题,并且大概确实如此。
class SharedA : public A
{
public:
SharedA(A* a) : mImpl(a){}
virtual void setX(int x) {mImpl->setX(x);}
virtual int getX() const {return mImpl->getX();}
private:
boost::shared_ptr<A> mImpl;
};
如果我可以创建一个模板类来为我处理所有这些,那将是 Grrrrrrrreat 的想法。
template <class T>
class Shared : public T
{
public:
SharedT(T* t) : mImpl(t)
{
//What kind of crazy voodoo goes here?
}
private:
boost::shared_ptr<T> mImpl;
};
如果我有这个(以及正确的构造函数Shared<T>
),那么我可以执行以下操作:
A* indestructo_A = new Shared<A>(new A(100));
A* indestructo_A_clone = new Shared<A>(indestructo_A);
delete indestructo_A
cout << "Indestructo-A back with a vengence!" << indestructo_A_clone.getX();
问题:
这有用吗?还是仅在您处理特别糟糕的代码的极端情况下才实用。例如:
void aFunctionYouHaveToUse(A* a) { /一些有用的算法然后/
删除 a; }是否可以构建这样的模板类?(我想你需要反思,对吧?)如果你能建造它,怎么建造?