vector::emplace_back for objects with a private constructor

前端 未结 2 1709
被撕碎了的回忆
被撕碎了的回忆 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:24

    You can use transfer-of-friendship semantics to avoid having to have a specialized vector allocator. It's a bit like dependency injection of friendship. This is really quite simple. You create an empty class who's makes itself a friend of your class. But the default constructor is private, so only your class can create instances of it. But the class is still copyable, so it can be passed to anybody.

    Your Timer constructor will be public, but it requires one of these objects as an argument. Therefore, only your class, or a function called by it, can create these objects directly (copies/moves will still work).

    Here's how you could do that in your code (live example):

    class TimerFriend
    {
    public:
      TimerFriend(const TimerFriend&) = default;
      TimerFriend& operator =(const TimerFriend&) = default;
    
    private:
      TimerFriend() {}
    
      friend class Timer;
    }
    
    class Timer {
        private:
            int timeLeft;
    
        public:
            Timer(unsigned int ms, const TimerFriend&) : timeLeft(ms) {}
    
            static std::vector instances;
            static void create(unsigned int ms) {
                instances.emplace_back(ms, TimerFriend());
            }
    };
    
    std::vector Timer::instances;
    

提交回复
热议问题