vector::emplace_back for objects with a private constructor

前端 未结 2 1715
被撕碎了的回忆
被撕碎了的回忆 2020-12-30 00:59

I want my Timer objects to be created via Timer::create() only. For this purpose, I made the constructor private. However, I get a compiler error saying that \"Timer::Timer(

2条回答
  •  太阳男子
    2020-12-30 01:51

    You probably should implement your own allocator, that will be friend to timer:

    class Timer {
    
        struct TimerAllocator: std::allocator
        {
            template< class U, class... Args >
            void construct( U* p, Args&&... args )
            {
                ::new((void *)p) U(std::forward(args)...);
            }
    
            template< class U > struct rebind { typedef TimerAllocator other; };
    
        };
        friend class TimerAllocator;
    
        private:
            int timeLeft;
    
        Timer(unsigned int ms) : timeLeft(ms) 
        {}
    
        public:
            static std::vector instances;
            static void create(unsigned int ms) {
                instances.emplace_back(ms);
            }
    };
    
    std::vector Timer::instances;
    
    int main()
    
    {
        Timer::create(100);
    }
    

    The simplest solution would be derive from std::allocator reimplementing rebind to rebind to itself, so vector couldn't rebind allocator back to std::allocator and implement own construct to actually create Timers.

提交回复
热议问题