lundi 1 juin 2020

About `std::unique_prt& pBase= make_unique

The fisrt code could not compile, whereas the second one could.Why?

These codes are almost the same indeed. I would be grateful to have some help with this question.

The code below could not compile. You could check it on http://cpp.sh/8j53y.

dynamic_cast
#include <iostream>
#include <memory>

using namespace std;

class Derived;

class Base { 
public:
    static unique_ptr<Base>& get_instance()
    {
        pBase = make_unique<Derived>();
        return pBase;
    }

private:
    static unique_ptr<Base> pBase;
};

class Derived: public Base { };

std::unique_ptr<Base> Base::pBase = nullptr;

int main () {

    auto& instance = Base::get_instance();
    return 0;
}

The code below could compile.

#include <iostream>
#include <memory>

using namespace std;

class Derived;

class Base { 
public:
    static unique_ptr<Base>& get_instance();

private:
    static unique_ptr<Base> pBase;
};

class Derived: public Base { };

std::unique_ptr<Base> Base::pBase = nullptr;

unique_ptr<Base>& Base::get_instance()
{
     pBase = make_unique<Derived>();
     return pBase;
}

int main () {
    auto& instance =  Base::get_instance();
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire