0

My goal is to take ownership of the temporary object created with Derived() in main() with BaseHolder.

I'm getting an error at m_bases.push_back(base) because it invokes Base::Base() which is illegal because it's a purely virtual class, but I don't understand why it's invoked in the first place because my thinking is that the already constructed object would just be moved into m_bases.

Is there a way to do what I'm trying to do here?

#include <vector>

using namespace std;

class Base {
public:
    virtual void foo() = 0;
};

class BaseHolder {
    vector<Base> m_bases;
public:
    void add(Base&& base) {
        m_bases.push_back(base);
    }
};

class Derived : public Base {
public:
    void foo() override {}
};

int main() {
    BaseHolder base_holder;
    base_holder.add(Derived());
    return 0;
}
andrey
  • 1,515
  • 5
  • 23
  • 39
  • 2
    Beware: Even if `Base` were *not* pure virtual, `vector` would still be a bad idea because it [slices](https://stackoverflow.com/q/274626/3282436) objects of type `Derived`. – 0x5453 Jun 18 '21 at 18:29
  • @0x5453 Noted, that would be pretty bad. – andrey Jun 18 '21 at 18:34
  • I think the only way to work around this is to allocate `Derived()` on the heap and hold onto something like `vector>` inside of `BaseHolder`. Alternatively you could ditch `Base` entirely and template `BaseHolder` on the derived type, but then you would not be able to mix derived types within a single `BaseHolder`. – 0x5453 Jun 18 '21 at 18:34
  • I'd be ok allocating `Derived` on the stack and using `vector m_bases` instead, but I'm getting `error: forming pointer to reference type ‘Base&’` on that line when I try that. – andrey Jun 18 '21 at 18:43
  • 1
    you can't make a vector of references: https://stackoverflow.com/questions/922360/why-cant-i-make-a-vector-of-references – Alan Birtles Jun 18 '21 at 18:46
  • 1
    If you want a vector of references, you can use [`std::reference_wrapper`](https://en.cppreference.com/w/cpp/utility/functional/reference_wrapper). But note that that will *not* take ownership of the `Derived` object. – 0x5453 Jun 18 '21 at 18:46

0 Answers0