vector :: emplace_back用于具有私有构造函数的对象 [英] vector::emplace_back for objects with a private constructor
问题描述
我希望我的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 Timer
s.
这篇关于vector :: emplace_back用于具有私有构造函数的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!