c – 从指针创建unique_ptr
发布时间:2020-12-16 10:09:52 所属栏目:百科 来源:网络整理
导读:以下代码给出了错误: void EntityContainer::AddChild(Entity* child) { unique_ptrEntity childPtr(child); children.push_back(childPtr);} 我认为这可能不是为现有对象创建unique_ptr的正确方法.怎么能这样做呢?上面的代码给出了以下错误: 1c:program
以下代码给出了错误:
void EntityContainer::AddChild(Entity* child) { unique_ptr<Entity> childPtr(child); children.push_back(childPtr); } 我认为这可能不是为现有对象创建unique_ptr的正确方法.怎么能这样做呢?上面的代码给出了以下错误: 1>c:program files (x86)microsoft visual studio 11.0vcincludexmemory0(617): error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>' 解决方法
您无法复制唯一指针.因为它们是……独特的.但是,您可以移动它们:
children.push_back(std::move(childPtr)); 这有点多余,所以你可以说: children.push_back(std::unique_ptr<Entity>(child)); 然而,安置施工已经提供了容器元件的直接构造: children.emplace_back(child); 然而,这些都没有达到标准.问题实际上是你有一个静默获取某些东西的功能,并且在界面中完全不可见.所以你应该更改函数签名并让调用者明确地给你所有权: void EntityContainer::AddChild(std::unique_ptr<Entity> child) { children.push_back(std::move(child)); } 现在,如果用户获得所有权语义错误,则不再是您的错! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |