标签:c iterator set move-semantics unique-ptr
我有一组unique_ptr实例,并希望将所有这些实例作为参数传递给函数.以下代码演示的示例.
#include <memory>
#include <set>
#include <vector>
using std::set;
using std::unique_ptr;
using std::vector;
void doStuff(unique_ptr<int> ptr)
{
// doing stuff...
}
int main()
{
vector<unique_ptr<int>> ptrVector;
set<unique_ptr<int>> ptrSet;
for (auto cur = ptrVector.begin(); cur != ptrVector.end(); cur++)
{
doStuff(std::move(*cur));
}
for (auto cur = ptrSet.begin(); cur != ptrSet.end(); cur++)
{
doStuff(std::move(*cur));
}
return 0;
}
这会导致以下编译器错误(GCC 4.8.1):
uptrfncall.cpp: In function ‘int main()’: uptrfncall.cpp:27:25: error: use of deleted function ‘std::unique_ptr::unique_ptr(const std::unique_ptr&) [with _Tp = int; _Dp = std::default_delete]’ doStuff(std::move(*cur)); // line 25, compiler error ^ In file included from /usr/include/c++/4.8/memory:81:0, from uptrfncall.cpp:1: /usr/include/c++/4.8/bits/unique_ptr.h:273:7: error: declared here unique_ptr(const unique_ptr&) = delete; ^ uptrfncall.cpp:9:10: error: initializing argument 1 of ‘void doStuff(std::unique_ptr)’ void doStuff(unique_ptr ptr) ^
请注意,它对矢量完美无缺,但不适用于集合.由于set不是const,因此begin()调用不应返回const_iterator,因此在取消引用迭代器时应该可以移动值.为什么这不编译?
解决方法:
该集合可能不是const,但其中的元素是.您无法修改集合的元素,因为它无法保证它保持其不变量.
标签:c,iterator,set,move-semantics,unique-ptr 来源: https://codeday.me/bug/20190723/1508902.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。