在以下代码示例中,我正在试验 std::unique_ptrs。我可以按照我的预期将 unique_ptr 添加到地图中。令我惊讶的是,我不能让它成为 std::pair 的成员。示例中的注释行应该我尝试构建与我的 map::value_type 具有相同类型(我认为...)的对。我不确定为什么这不起作用。
提前致谢。
#include <iostream>
#include <memory>
#include <map>
#include <arpa/inet.h>
typedef std::map<uint32_t, std::unique_ptr<uint32_t> > ntohl_map_type;
typedef std::map<uint32_t, uint32_t> u32_map_type;
void
u32_map()
{
uint32_t key(0);
uint32_t val(0);
u32_map_type u32_map;
u32_map.insert(u32_map_type::value_type(key, val));
u32_map.insert(std::pair<uint32_t, uint32_t>(++key, ++val));
std::cout << "u32_map: " << std::endl;
for (auto &itr : u32_map) {
std::cout << itr.first << " = " << itr.second << "\n";
}
std::cout << std::endl;
}
void
uptr_map()
{
uint32_t key(9);
std::unique_ptr<uint32_t> u32_uptr1(new uint32_t(ntohl(key)));
ntohl_map_type ntohl_map;
ntohl_map.insert(ntohl_map_type::value_type(key, std::move(u32_uptr1)));
++key;
std::unique_ptr<uint32_t> u32_uptr2(new uint32_t(ntohl(key)));
// It seems odd these don't work....
//foo = std::pair<uint32_t, std::unique_ptr<uint32_t>(key, std::move(u32_uptr2));
//ntohl_map.insert(std::pair<uint32_t, std::unique_ptr<uint32_t>(key, std::move(u32_uptr2)));
std::cout << "uptr_map: " << std::endl;
for (auto &itr : ntohl_map) {
std::cout << itr.first << " = " << *itr.second << "\n";
}
}
int
main()
{
u32_map();
uptr_map();
return 0;
}
编辑:刚刚意识到编译器错误可能会有用:
error: no matching constructor for initialization of 'std::unique_ptr<uint32_t>'
...const, std::unique_ptr<uint32_t>(key, std::move(u32_uptr2)));
^ ~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/bin/../lib/c++/v1/memory:2554:31: note: candidate constructor not viable: no known conversionfrom 'uint32_t' (aka 'unsigned int') to 'pointer' (aka 'unsigned int *') for 1st argument; take the address of the argument with &
_LIBCPP_INLINE_VISIBILITY unique_ptr(pointer __p, typename conditional<
^
/usr/bin/../lib/c++/v1/memory:2561:31: note: candidate constructor not viable: no known conversion from 'uint32_t' (aka 'unsigned int') to 'pointer' (aka 'unsigned int *') for 1st argument; take the address of the argument with &
_LIBCPP_INLINE_VISIBILITY unique_ptr(pointer __p, typename...