简体   繁体   中英

How to declare a shared pointer in member initialization list

I'm trying to add a shared pointer to my initialization list. This pointer has already been declared in my header file. Once i add it to the list, the compiler errors out with error: no matching function for call to std::shared_ptr<memory::Mmu>::shared_ptr(std::shared_ptr<Cartridge>&)

header file:

class Gameboy {
    public:
        Gameboy(std::vector<uint8_t>);
        void run();
    private:
        void tick();
        std::shared_ptr<Cartridge> cartridge;
        std::shared_ptr<memory::Mmu> mmu;
};

c file:

Gameboy::Gameboy(std::vector<uint8_t> cartridgeData)
    : cartridge(getCartridge(std::move(cartridgeData))),
      mmu(cartridge)
    {

    }

mmu.h


namespace memory {
    class Mmu {
        public:
            std::shared_ptr<Cartridge> cartridge;
            Mmu(std::shared_ptr<Cartridge>&);

        private:
            bool bootRomActive() const;
    };
}

I expect it to call the mmu constructor which takes std::shared_ptr<Cartridge>& as first param.

std::shared_ptr<T> does not have a constructor that accepts a std::shared_ptr<Y> when Y does not derive from T .

Assuming your Cartridge does not derive from memory::Mmu (you did not show the declaration of Cartridge ), then you cannot construct a std::shared_ptr<memory::Mmu> directly from a std::shared_ptr<Cartridge> . Hence the error message.

If you need to construct a new memory::Mm that references a Cartridge , then in the Gameboy member initialization list, change this:

mmu(cartridge)

To either:

mmu(new memory::Mm(cartridge))

Or:

mmu(std::make_shared<memory::Mm>(cartridge))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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