vector :: emplace_back用于具有私有构造函数的对象 [英] vector::emplace_back for objects with a private constructor

查看:125
本文介绍了vector :: emplace_back用于具有私有构造函数的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的Timer对象通过Timer :: create()创建。为了这个目的,我使构造函数私有。但是,在new_allocator.h的上下文中,我得到一个编译器错误,说Timer :: Timer(unsigned int)'是private。我如何解决这个问题?

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(unsigned int)' is private" within the context of new_allocator.h. How can I solve this problem?

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 to timer:

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

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 以重新绑定自身,因此向量分配器返回到 std :: allocator 并实现自己的构造以创建 Timer s。

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

这篇关于vector :: emplace_back用于具有私有构造函数的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆