簡體   English   中英

unique_ptr 的問題

[英]Issue with unique_ptr

誰能告訴我這段代碼有什么問題? 它拋出一個錯誤:

無法將參數 1 從 '_Ty' 轉換為 '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()new的智能指針等價物,這意味着它調用指定類型的構造函數,將輸入參數傳遞給該構造函數,並返回指向新對象的std::unique_ptr

該聲明:

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

因此等價於:

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

我很確定這不是你要寫的。

如果您只想將原始指針轉換為std::unique_ptr ,請直接構造std::unique_ptr並且不要使用std::make_unique()

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

否則,使用std::make_unique()構造Instruction<char>而不是BaseInstruction

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM