C++11 emplace_back on vector?

前端 未结 8 658
借酒劲吻你
借酒劲吻你 2020-12-02 14:58

Consider the following program:

#include 
#include 

using namespace std;

struct T
{
    int a;
    double b;
    string c;
};

         


        
8条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-02 15:36

    If you do not want to (or cannot) add a constructor, specialize allocator for T (or create your own allocator).

    namespace std {
        template<>
        struct allocator {
            typedef T value_type;
            value_type* allocate(size_t n) { return static_cast(::operator new(sizeof(value_type) * n)); }
            void deallocate(value_type* p, size_t n) { return ::operator delete(static_cast(p)); }
            template
            void construct(U* p, Args&&... args) { ::new(static_cast(p)) U{ std::forward(args)... }; }
        };
    }
    

    Note: Member function construct shown above cannot compile with clang 3.1(Sorry, I don't know why). Try next one if you will use clang 3.1 (or other reasons).

    void construct(T* p, int a, double b, const string& c) { ::new(static_cast(p)) T{ a, b, c }; }
    

提交回复
热议问题