최대 1 분 소요

개요

  • 다형성을 이용해 allocator는 polymorphic_allocator 하나를 쓰고 세부 구현은 memory_resource에 따라 동작
  • 서로 다른 allocator를 사용하는 경우 assign이 불가한 문제를 해결


예제

  • 코드
    #include <iostream>
    #include <memory_resource>
    #include <vector>

    using namespace std;

    template <class T> struct custom_allocator {
    		typedef T value_type;
    		custom_allocator() noexcept {}
    		template <class U>
    		custom_allocator(const custom_allocator<U> &) noexcept {}
    		T *allocate(std::size_t n) {
    			return static_cast<T *>(::operator new(n * sizeof(T)));
    		}
    		void deallocate(T *p, std::size_t n) { ::delete (p); }
    };

    int main() {
    	{
    		vector<int> v0;
    		vector<int, custom_allocator<int>> v1;

    		/* compile error
    		v0 = v1;
    		*/
    	}

    	{
    		pmr::synchronized_pool_resource sync_pool;
    		pmr::unsynchronized_pool_resource unsync_pool;

    		pmr::vector<int> v0{{0, 1, 2, 3, 4}, &sync_pool};
    		pmr::vector<int> v1{{5, 6, 7, 8, 9}, &unsync_pool};

    		v0 = v1;

    		for (const auto &iter : v0) {
    			cout << iter << endl;
    		}
    	}

    	return 0;
    }
  • 실행 결과
    5
    6
    7
    8
    9