I have the following C++11 construct:
#include <vector>
#include <memory>
class X {
public:
        void f(void) { }
};
class Y : public X {
public:
        void g(void) { }
};
class A {
private:
        std::vector <std::unique_ptr <X> > xs;
public:
        void addX(std::unique_ptr <X> &ref) {
                xs.push_back(std::move(ref));
        }
};
int main() {
        A a;
        std::unique_ptr <Y> y(new Y());
        y->f();
        y->g();
        std::unique_ptr <X> x(y.release());
        a.addX(x);
        return 0;
}
In the main function I am trying to build an object of type Y and then add it to the vector of X objects of a. However, I can not directly say a.addX(y) as std::unique_ptr <Y> cannot be cast to std::unique_ptr <X>&. This is why I came up with the workaround where I initialize another unique pointer, x, with the released internal pointer of y.
Although this works, it doesn't seem like the best solution. Is there a better way of passing an object of type std::unique_ptr<Y> as an argument of type std::unique_ptr<X>&?
Thanks, - Stan
 
    