首页 > 解决方案 > Unique_ptr 超出范围

问题描述

我在将 unique_ptrs 传递给函数时遇到问题,当我传递给 askQuestion 时,它们似乎超出了范围。

听到我的密码。

char askQuestion(string *questions[8], unique_ptr<binaryBase>answered) {
    bool asked = false;
    char input = '0';
    while (!asked) { // loop until you find a question that has not been asked
        int randomQuestion = (rand() % 8); // generate a random number
        if (!(answered->getBit(randomQuestion))) { // check if the question has been answered 
            getInput(input, *questions[randomQuestion]);
            answered->toggleBit(randomQuestion);
            asked = true;
        }
    }
    return input;
}

这两个函数访问 unique_ptrs,下面的函数依赖上面的函数进行输入。当我调用 askQuestion 时,我得到“(变量)不能被引用——它是一个已删除的函数”


bool checkAnswer(char answer, int place, binaryBase* reference) {
/*  if the answer is T and the correct answer is true, returns true
    if the answer is F and the correct answer is false, returns true
    return false otherwise
*/ return((answer=='T'&&reference->getBit(place))||(answer=='F'&&!reference->getBit(place)));
}

binaryBase 是一个简单的自定义类,只有 8 个 int 作为数据,以及用于位的 getter 和 setter,这将 8 位 int 视为一个字节来存储程序的“布尔”答案。

标签: c++unique-ptr

解决方案


askQuestion()在您的示例中,我没有看到调用。但是,我可以看到这askQuestion()answered参数的“观察者”。unique_ptr 用于转移指针的所有权,而不仅仅是观察它。因此,您应该将该函数定义为:

char askQuestion(string *questions[8], binaryBase& answered)

反而。在此处使用引用而不是指针来明确表示不允许传递 null。(当然改变所有出现的answered->to answered.

当您调用该函数并希望传递由 a 管理的unique_ptr<binaryBase> ptr对象时,请传递托管对象,而不是 unique_ptr 本身*ptr

如果您确实想要转移指针的所有权,则需要移动指针:

void func(std::unique_ptr<binaryBase>);

// ...
std::unique_ptr<binaryBase> ptr = /* ... */
func(std::move(ptr));

调用func(),后ptr不再包含对象。func()拥有它。

unique_ptr是“只移动类型”。它不能被复制,因为它的复制构造函数和复制赋值运算符已被删除,这是你原来编译错误的原因。


推荐阅读