在下面的代码示例中,我正在尝试使用std::unique_ptrs。我可以像预期的那样将unique_ptr添加到map中。让我惊讶的是,我不能将其作为std::pair的成员。示例中的注释行应该是我尝试构造与我的map::value_type相同类型的pair(我认为...)。我不确定为什么这不起作用。
提前感谢。
提前感谢。
#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...
const
。在发布代码之前,我已经尝试过并且编译成功了(请参见此实时示例)。 - Andy Prowl