c++ - 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 视为一个字节来存储程序的“布尔”答案。
解决方案
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
是“只移动类型”。它不能被复制,因为它的复制构造函数和复制赋值运算符已被删除,这是你原来编译错误的原因。
推荐阅读
- java - Scanner.nextInt(); 正在接受两个输入(我认为)
- javascript - 你能帮我解释一下 Sass 代码中的 `&` 吗?
- java - 在内存管理方面,定义全局变量优于局部变量的好处
- javascript - 选中复选框时调用 Ajax 或提交按钮
- python - python循环遍历字典键内的多个列表(已编辑)
- postgresql - peewee.ProgrammingError:列必须出现在 GROUP BY 子句中或在聚合函数中使用
- javascript - Running two showDiv() functions on the same page
- c++ - 两个 cin / cout 语句合并为一个
- r - 在 R 中的数据框中搜索文本
- redux - Redux-Saga ES6 类语法方法不会在动作调度时被调用