Casting between unique_ptr in C ++

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 try to build an object of type Y, and then add it to the vector X of objects a. However, I cannot directly say a.addX(y), because std::unique_ptr <Y>it cannot be added to std::unique_ptr <X>&. This is why I came up with a workaround when I initialize another unique pointer x with an issued internal pointer y.

Although this works, it does not seem like a better solution. Is there a better way to pass a type object as std::unique_ptr<Y>a type argument std::unique_ptr<X>&?

Thanks, Stan

+3
source share
2 answers

std:: unique_ptr , std:: move , unique_ptr :

std::unique_ptr<X> x;
std::unique_ptr<Y> y { new Y };
x = std::move(y);

, unique_ptr , .

template < typename T, typename = typename std::enable_if< std::is_base_of<X,T>::value>::type >
void foo( std::unique_ptr<T> & ) {
}

, , , unique_ptr rvalue, , .

void bar( std::unique_ptr<X> && ) {
}
// then
bar( std::move(y) );
+5

rvalue std:: move:

#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() {
        std::unique_ptr <Y> y(new Y());
        y->f();
        y->g();

        A a;
        a.addX(std::move(y));

        // error: no matching function for call to ‘A::addX(std::unique_ptr<Y>&)’
        // a.addX(y);

        return 0;
}

void addX(std::unique_ptr <X> &ref) .

+2

All Articles