我是智能指针的新手,如果有人能给我一个暗示,我是否正在处理智能指针作为类成员是否正确,我将非常感激。 更确切地说,我想要实现的解决方案是在类多态的上下文中,理想情况下应该是异常安全的。
给定container of heterogeneuous objects(std::vector<shared_ptr<CBase> > my_vector
),添加元素的常用方法是:my_vector.push_back( shared_ptr<CBase>(new CChild(1)))
,以便稍后可以通过执行调用特定派生类的成员函数:my_vector[0]->doSomething()
。
我想要实现的是将堆栈对象添加到向量中,并且仍然能够进行多态性。直觉......喜欢:CChild<float> obj1(1); my_vector.push_back(obj1)
。要解决这个问题,我现在使用Virtual Constructor Idiom:CChild obj1(1); my_vector.push_back(obj1.clone());
请注意,在我的派生类的some
中,我有创建对象的静态成员函数,例如:CChild<float> obj1 = CChild<float>::initType2(1);
由于需求问题以及干净的界面,我现在有一个新的类CFoo<T>
,它具有作为数据成员的指向CBase<T>
类的智能指针。
这个想法是,除了包含其他新的私人成员,
这个类封装/处理派生对象的智能指针,这样我就可以做了。喜欢:
CFoo<float> myfoo(CChild<float>::initType2(1)); my_vector.push_back(myfoo);
。这意味着容器现在是vector<CFoo<T> >
类型而不是类型vector<shared_ptr<CBase> >
正是在这种情况下,我想知道如何为smart pointers
类作为类成员的类实现构造函数?如何在复制交换习惯用法之后实现operator =
?下面,我对我的班级设计进行了一些阐述:
template < typename T >
class CBase{
public:
CBase(){};
virtual ~CBase(){};
...
virtual CBase<T> * clone() const = 0;
virtual CBase<T> * create() const = 0;
};
template < typename T >
class CChild1 : public CBase{
public:
...
CChild1<T> * clone() const { return new CChild1<T>(*this); }
CChild1<T> * create() const { return new CChild1<T>(); }
static CChild1 initType1(double, double);
static CChild1 initType2(int);
};
template < typename T >
struct type{
typedef std::tr1::shared_ptr<T> shared_ptr;
};
template < typename T >
class CFoo{
public:
CFoo();
CFoo( const CBase<T> &, int = 0 );
CFoo( const CFoo<T> & );
void setBasePtr( const CBase<T> & );
void swap( CFoo<T> & );
CFoo<T> & operator = ( CFoo<T> );
...
~CFoo();
private:
typename type<CBase<T> >::shared_ptr m_ptrBase;
int m_nParam;
};
template < typename T >
CFoo<T>::CFoo()
:m_nParam(0)
// How shall I handle here the "m_ptrBase" class member? e.g point it to NULL?
{
}
template < typename T >
CFoo<T>::CFoo(const CBase<T> & refBase, int nParam)
:m_ptrBase(refBase.clone()), // Is this initialization exception-safe?
m_nParam(nParam)
{
}
template < typename T >
CFoo<T>::CFoo(const CFoo<T> & refFoo)
:m_ptrBase(refFoo.m_ptrBase),
m_nParam(refFoo.m_nParam)
{
}
template < typename T >
void CFoo<T>::setBasePtr( const CBase<T> & refBase ){
// ??? I would like to do sth. like: m_ptrBase(refBase.clone())
}
template < typename T >
CFoo<T>::~CFoo(){
// The memory is going to be freed by the smart pointer itself and therefore
// the destructor is empty, right?
}
template < typename T >
void CFoo<T>::swap( CFoo<T> & refFoo ){
//does this here makes sense?
using std::swap;
swap(m_ptrBase, refFoo.m_ptrBase);
swap(m_nParam, refFoo.m_nParam);
}
template < typename T >
CFoo<T> & CFoo<T>::operator = ( CFoo<T> copyFoo ){
copyFoo.swap(*this);
return (*this);
}
下面是一个我想直观地实现的例子。首先,我使用包含指向派生类的智能指针的CFoo<float>
对象填充容器,此外还有另一个整数类成员(请注意,所有这些只是说明性的。)
std::vector<CFoo<float> > my_bank;
for (int b=0; b < 3; b++){
float x = b*sqrt(2);
my_bank.push_back( new CFoo<float>( CChild1<float>::initType2(x), b) );
}
for (double s= 1.0; s<= 8.0; s *= 2.0){
my_bank.push_back( new CFoo<float>( CChild2<float>::initType2(x), 0) );
}
一旦容器被填满,我想做一些操作,呼叫virtual
功能,例如doSomething
专门用于每个派生类。
for (int i=0; i < (int)my_bank.size(); i++){
int b = my_bank[i].m_nParam;
CBase<float>* myChild = my_bank[i].m_ptrBase;
myChild->doSomething( param1, param2, param3, ..., b);
}
答案 0 :(得分:3)
我真的不知道如何处理这个问题。我不明白你列出的接口要求的一半,所以请考虑这个可能与你的问题无关的实验性答案。
我建议您告诉我我的方法究竟缺少什么,我可以修改它。我现在将省略模板,因为它们似乎与问题无关。
所以,不用多说,最简单的开始使用一个智能指针容器:
#include <vector>
#include <memory>
struct Base
{
virtual void f();
};
typedef std::shared_ptr<Base> BasePtr;
typedef std::vector<BasePtr> BaseContainer;
struct DerivedA : Base
{
virtual void f();
// ...
};
// further derived classes
用法:
int main()
{
BaseContainer v;
v.push_back(BasePtr(new DerivedB));
v.push_back(BasePtr(new DerivedC(true, 'a', Blue)));
BasePtr x(new DerivedA);
some_func(x);
x->foo()
v.push_back(x);
v.front()->foo();
}
如果您碰巧在某处有自动对象,可以插入副本:
DerivedD d = get_some_d();
v.push_back(BasePtr(new DerivedD(d)));
迭代:
for (BaseContainer::const_iterator it = v.begin(), end = v.end(); it != end; ++it)
{
(*it)->foo();
}
更新:如果您想在构建后初始化对象,可以执行以下操作:
{
DerivedE * p = new DerivedE(x, y, z);
p->init(a, b, c);
v.push_back(BasePtr(p));
}
或者,如果init
函数是虚拟的,甚至更简单:
v.push_back(BasePtr(new DerivedE(x, y, z)));
v.back()->init(a, b, c);
第二次更新:以下是派生对象的外观:
struct DerivedCar : Base
{
enum EType { None = 0, Porsche, Dodge, Toyota };
DerivedCar(EType t, bool a, unsigned int p)
: Base(), type(t), automatic_transmission(a), price(p)
{
std::cout << "Congratulations, you know own a " << names[type] << "!\n"; }
}
private:
EType type;
bool automatic_transmission;
unsigned int price;
static const std::unordered_map<EType, std::string> names; // fill it in elsewhere
};
用法:Base * b = new DerivedCar(DerivedCar::Porsche, true, 2000);
第3次更新:这个是未连接的,只是说明了如何使用查找表来支持switch语句。假设我们有许多类似的函数(相同的签名),我们想要根据一些整数使用它们:
struct Foo
{
void do_a();
void do_b();
// ...
void do(int n)
{
switch (n) {
case 2: do_a(); break;
case 7: do_b(); break;
}
}
};
我们可以在查找表中注册所有函数,而不是切换。这里我假设C ++ 11支持:
struct Foo
{
// ...
static const std::map<int, void(Foo::*)()> do_fns;
void do(int n)
{
auto it = do_fns.find(n);
if (it != do_fns.end()) { (this->**it)(); }
}
};
const std::map<nt, void(Foo::*)()> Foo::do_fns {
{ 3, &Foo::do_a },
{ 7, &Foo::do_b },
// ...
};
基本上,您将静态代码转换为容器数据。这总是一件好事。现在这很容易扩展;您只需在查找映射中添加新函数即可。无需再次触摸实际的do()
代码!