简体   繁体   English

存储子类指针的方法

[英]method storing subclass pointers

I have superclass A and subclasses B and C , 我有超类A和子类BC

I have to satisfy sort of an interface in a sense that I want to do something like this: 从某种意义上说,我必须满足某种接口要求:

x.Add(B());

or 要么

x.Add(C());

or any other subclass of an A. where B() and C() are default construtors my Add method looks like this: 或A的任何其他子类B()C()是默认构造C()我的Add方法如下所示:

Add(A & data){
vector<A*> vec;
vec.push_back(new A())
}`

its giving me an error invalid initialization of non-const reference of type 'A&' from an rvalue of type 'A' 它给我一个错误invalid initialization of non-const reference of type 'A&' from an rvalue of type 'A'

What is the problem here? 这里有什么问题?

You are constructing temporary objects, which cannot be assigned to a non-const reference. 您正在构造不能分配给非常量引用的临时对象。 You would have to make the parameter be a const reference instead: 您将必须使该参数成为const引用:

class MyClass
{
public:
    void Add(const A &data);

private:
    std::vector<A*> vec;
};

void MyClass::Add(const A &data)
{
    vec.push_back(&data);
}

MyClass x;
x.Add(B());
x.Add(C());

But it does not really make sense to store pointers to temporary objects, since they will be destroyed, leaving the vector holding invalid pointers. 但是,存储指向临时对象的指针实际上没有任何意义,因为它们将被破坏,从而使矢量保存无效的指针。

So, one option would be to push caller-allocated pointers instead: 因此,一种选择是改为推送调用者分配的指针:

class MyClass
{
public:
    void Add(A *data);

private:
    std::vector<A*> vec;
};

void MyClass::Add(A *data)
{
    vec.push_back(data);
}

MyClass x;
x.Add(new B);
x.Add(new C);

But that can cause memory leaks if vec.push_back() fails. 但是,如果vec.push_back()失败,则可能导致内存泄漏。

Another option is to let Add() itself perform the allocation internally, and free it if something goes wrong: 另一个选择是让Add()本身在内部执行分配,并在出现问题时释放它:

class MyClass
{
public:
    template <typename T>
    void Add()
    {
        std::auto_ptr<T> data(new T);
        vec.push_back(data.get());
        data.release();
    }

private:
    std::vector<A*> vec;
};

MyClass x;
x.Add<B>();
x.Add<C>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM