我在使用包含 unique_ptr 的结构时在 C++ 中遇到了一些麻烦。 该结构的一部分是
struct test {
std::vector <std::unique_ptr<function>> allFunctions;
}
在哪里
function
是另一个结构。我总是让 C2280 尝试引用已删除的函数
正如您可能怀疑的那样,我是 C++ 的新手,经验不多。 而且我必须使用 unique_ptr,因为这是练习的一部分。
非常感谢您的帮助! :)
最佳答案
错误在使用test
的代码中,即您未显示的代码。
std::unique_ptr
根据定义是不可复制的(它是独一无二的!)。这使得您的整个结构不可复制。
如果您尝试复制 test
在某处,编译器会告诉你没有 std::unique_ptr::operator =
, 这是复制所需要的。
例如:
test x;
test y = x; // Copying. Error C2280
或者
void someFunction(test x) {}
int main() {
test x;
someFunction(x); // Copying. Error C2280
}
Error C2280 'std::unique_ptr<function,std::default_delete<_Ty>> &std::unique_ptr<_Ty,std::default_delete<_Ty>>::operator =(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)': attempting to reference a deleted function
解决方案是避免复制test
.您可以通过引用传递它来实现这一点。
void someFunction(test& x) {}
int main() {
test x;
someFunction(x); // OK
}
关于c++ - vector 中的 Unique_ptr 作为结构的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50304500/