简体   繁体   中英

Issue with unique_ptr

Can anyone tell me what the issue is with this code? It throws an error:

cannot convert argument 1 from '_Ty' to 'const day18::BaseInstruction &'

    enum Command { snd, set, add, mul, mod, rcv, jgz };
    struct BaseInstruction {
        Command cmd;
        char reg;
        BaseInstruction(Command cmd, char reg)
            :cmd{cmd}, reg{reg}
        {}
    };
    template <typename T>
    struct Instruction : public BaseInstruction {
        T val;
        Instruction(Command cmd, char reg, T val)
            :BaseInstruction(cmd, reg), val{ val }
        {}
    };
    std::unique_ptr<BaseInstruction> getInstructionPtr(Command cmd, char reg, std::string valStr) {
        const static std::regex nr("-?\\d+");
        if (valStr.length() == 0) return std::make_unique<BaseInstruction>(new BaseInstruction(cmd, reg));
        if (std::regex_match(valStr, nr)) return std::make_unique<BaseInstruction>(new Instruction<int>(cmd, reg, std::stoi(valStr)));
        return std::make_unique<BaseInstruction>(new Instruction<char>(cmd, reg, valStr[0]));
    }

std::make_unique() is the smart-pointer equivalent of new , which means it calls the constructor of the specified type, passing the input parameters to that constructor, and returns a std::unique_ptr that points to the new object.

The statement:

std::make_unique<BaseInstruction>(new Instruction<char>(...));

is therefore equivalent to this:

new BaseInstruction(new Instruction<char>(...))

I'm quite sure that's not what you meant to write.

If you just want to convert a raw pointer to a std::unique_ptr , construct the std::unique_ptr directly and don't use std::make_unique() :

return std::unique_ptr<BaseInstruction>(new Instruction<char>(...));

Otherwise, use std::make_unique() to construct Instruction<char> instead of BaseInstruction :

return std::make_unique<Instruction<char>>(...);

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