我希望仅通过Timer::create()创建我的Timer对象。为此,我将构造函数设为私有(private)。但是,在new_allocator.h的上下文中,我收到一个编译器错误,指出“Timer::Timer(unsigned int)'是私有(private)的”。我怎么解决这个问题?

class Timer {
    private:
        int timeLeft;
        Timer(unsigned int ms) : timeLeft(ms) {}

    public:
        static std::vector<Timer> instances;
        static void create(unsigned int ms) {
            instances.emplace_back(ms);
        }
};

std::vector<Timer> Timer::instances;

最佳答案

您可能应该实现自己的分配器,这将成为计时器的 friend :

class Timer {

    struct TimerAllocator: std::allocator<Timer>
    {
        template< class U, class... Args >
        void construct( U* p, Args&&... args )
        {
            ::new((void *)p) U(std::forward<Args>(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<Timer, TimerAllocator> instances;
        static void create(unsigned int ms) {
            instances.emplace_back(ms);
        }
};

std::vector<Timer, Timer::TimerAllocator> Timer::instances;

int main()

{
    Timer::create(100);
}

最简单的解决方案是通过std::allocator<Timer>重新实现rebind来重新绑定(bind)到自身,因此vector无法将分配器重新绑定(bind)回std::allocator并实现自己的construct来实际创建Timer

08-16 18:03
查看更多