gpt4 book ai didi

c++ - Unique_ptr超出范围

转载 作者:行者123 更新时间:2023-12-02 09:55:56 25 4
gpt4 key购买 nike

我在将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视为一个字节,以存储程序的“ bool(boolean) ”答案。

最佳答案

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

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

代替。在此处使用引用而不是指针来明确表示不允许传递null。 (当然,将所有出现的 answered->更改为 answered.)

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

如果确实要转移指针的所有权,则需要移动指针:
void func(std::unique_ptr<binaryBase>);

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

调用 func()之后, ptr不再包含任何对象。 func()拥有它的所有权。
unique_ptr是“仅移动类型”。无法复制它,因为它的复制构造函数和复制赋值运算符已删除,这是原始编译错误的原因。

关于c++ - Unique_ptr超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60133195/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com