다음 코드 샘플에서 std :: unique_ptrs를 실험하고 있습니다. unique_ptr을 맵에 추가 할 수 있습니다. 나에게 놀라운 것은 내가 std :: pair의 멤버가 될 수 없다는 것이다. 이 예제에서 주석 처리 된 행은 my map :: value_type과 동일한 유형 (내 생각에는 ...) 인 쌍을 구성해야합니다. 왜 이것이 작동하지 않는지 모르겠습니다.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...
나는 그것이 문제라고 생각하지 않는다. 먼저 u32_map 함수에서 그렇게 할 필요가 없다는 것을 알게 될 것입니다. 또한 내가 (value_type을 사용하여) 마지막 빛을 이미 가지고 있다는 것을 알았다면 나는 단지 그것들이 동등한 진술이라고 생각했고 나는 왜 하나가 작동하고 다른 하나는 그렇지 않은지 이해하지 못한다. – user2466803
@ user2466803 : 마지막 편집에서 답을 설명하려고했습니다. 업데이트 된 답변을 확인하십시오. 또한, 내가 제안한 것을 시도해보십시오 - 코드 컴파일을 보게 될 것입니다. –
아, 복사 구성이 의미가 있습니다. 귀하의 솔루션은 여전히 나를 위해 컴파일되지 않습니다. 복사를 피하려면 다음과 같이 std :: pair를 이동하십시오 :: ntohl_map.insert (std :: move> (key, std : : move (u32_uptr2))))); –
user2466803