In the following code sample I am experimenting with std::unique_ptrs. I am able to add the unique_ptr to a map as I would expect. What is surprising to me is that I cannot make it a member of a std::pair. The commented lines in the example should my trying to construct a pair that is of the same type (I think...) as my map::value_type. I am not sure why this doesn't work.
Thanks in advance.
#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;
}
EDIT: Just realized the compiler error would probably be useful:
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...