할당 자 유형 (표준 섹션 17.6.3.5에 정의 된대로)을 템플릿 인수로 취하는 클래스 템플릿을 디자인하고 싶습니다. A
의 누락 된 회원을 std::allocator_traits<A>
이 유용하게 채우는 것을 봅니다. 그 외에도, 표준 라이브러리 나 할당자를 올바르게 사용하는 데 도움이되는 사항이 있습니까? 특히std :: allocator_traits의 사용 <A>
:
이
std::allocator_traits<A>::propagate_on_container_copy_assignment
같은 형식 정의를 존중하기 위해, 나는 형A
의 멤버가 각 클래스의 특정 멤버 함수에 이런 일을 확인해야합니까? 아니면이 물건을 처리 할 멤버 대신 사용할 수있는 래퍼 유형이 있습니까?사용자가 볼 수있는 개체 옆에 여분의 데이터를 저장하여 할당 횟수를 줄이기 위해 전체 할당을하려면 할당자를 이와 같이 리 바인드하는 것이 적절합니까?
.
template<typename T, typename A>
class MyClass
{
private:
//...
struct storage {
int m_special_data;
T m_obj;
};
typedef typename std::allocator_traits<A>::template rebind_alloc<storage>
storage_alloc;
typedef typename std::allocator_traits<A>::template rebind_traits<storage>
storage_traits;
storage_alloc m_alloc;
static T* alloc(T&& obj)
{
storage_traits::pointer sp = storage_traits::allocate(m_alloc, 1);
sp->m_special_data = 69105;
return ::new(&sp->m_obj) T(std::move(obj));
}
//...
};
"storage_traits :: construct (m_alloc, &sp);', 또는 'rebind'로 인해 계산되지 않습니까?) '저장소를 구성하면 어떻게됩니까? ''T'' 타입의 멤버를 가지고 있다면 멤버는'storage'가 아니라'storage'와 함께 생성됩니다. 그래서''union'' 또는'static_cast''를' – aschepler
@aschepler, +1, well spotted! 지금 고쳐 주신 고마워요 –
두 번째 질문에 네, 합집합을 사용하거나 알맞은 크기로 배열 된'char' 배열을 사용할 수 있습니다. 'storage'가'T'와는 별개로 구성 가능한 데이터만을 포함하고 있는지 확인하는 것이 더 쉽기 때문에'T'를'생성 '하고 단순히 다른 부분 (대개 포인터 및/또는 정수)에 값을 할당 할 수 있습니다. 내 대답을 편집 할게. 그것을 반영하기 위해. –