2016-12-27 2 views
1

vector<unique_ptr<T>>vector<unique_ptr<const T>>으로 변환하는 방법?벡터 <unique_ptr <T>>을 (를) 벡터로 변환하십시오. <unique_ptr <const T>>

reinterpret_cast을 사용하면 어떤 단점이 있습니까? C++ 11 이상에서 그렇게하는 것이 좋습니다.

vector<unique_ptr<const T>> Get() { 
    vector<unique_ptr<T>> some; 
    ... 
    // Any better way to do this? 
    return *(reinterpret_cast<vector<unique_ptr<const T>>*>(&some)); 
} 
+0

그냥'return {some.begin(), some.end()}'하면 되나요? –

+0

@BenVoigt : 고유 포인터는 복사 할 수 없습니다. –

+0

@Kerrek : 아 맞아. 이동 반복 어댑터가 필요합니다. 새로운 벡터에서 기존의 모든 unique_ptr 을'unique_ptr '으로 옮기는 것이 올바른 접근법이다. 왜냐하면'reinterpret_cast'는 UB이기 때문이다. –

답변

4

당신은 그것으로 오래된 벡터의 내용을 이동하여 새로운 벡터를 생성 할 수 있습니다 : 정의되지 않은 동작에

#include <iterator> 
#include <memory> 
#include <vector> 

std::vector<std::unique_ptr<T>> v; // ... 

std::vector<std::unique_ptr<const T>> cv(
    std::make_move_iterator(v.begin()), 
    std::make_move_iterator(v.end())); 

귀하의 제안 reinterpret_cast 결과를.

질문의 일반적인 주제는 리소스 관리 처리기가 다른 관련 작업 인 것처럼 한 가지를 시도하는 것입니다. 핸들러가 실제로 핸들링이 정확히 무엇인지 알아야하기 때문에 이것은 문제가되는 개념이며, 다소 요점을 놓치고 있습니다. 무엇을하고 싶은지 건에 대해 의견을 교환하십시오. 현재 컨텍스트에서 핸들 된 객체 인 T 포인터를 가지고 인을 일반적인 언어 규칙을 사용하여 const T 포인터로 변환 할 수 있습니다. 이는 예상대로 작동하며 핸들러 개체 (고유 포인터)에 대한 설명을 피합니다.

+0

[데모] (https://ideone.com/kOMvYg) –

1

당신이 소유권을 이전하지 않으려는 것을 가정 할 때, 당신은 관찰자 포인터의 벡터를 만들 수 있습니다

template<class T> 
using const_observer_ptr = const T*; 

template<class T> 
auto Get() { 
    std::vector<const_observer_ptr<T>> some; 

    some.resize(source.size()); 
    std::transform(source.begin(), source.end(), some.begin(), 
        [](auto&& unique) { return unique.get(); }); 
    return some; 
} 

그런 다음, 개체를 이동 다른 답변을보고 싶다면

.

관련 문제