私のTimerオブジェクトをTimer :: create()だけで作成します。この目的のために、私はコンストラクタを非公開にしました。しかし、私は、コンパイラのエラーは、 "Timer :: Timer(unsigned int) 'がnew_allocator.hのコンテキスト内でprivateであるというエラーが出ます。どうすればこの問題を解決できますか?最も簡単な解決策は、それ自体に再バインドするrebind
を再実装std::allocator<Timer>
から派生することになるので、vector
は再バインドできませんでしプライベートコンストラクタを持つオブジェクトのvector :: emplace_back
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);
}
:
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;
、唯一の理由は、 'コピー/移動コンストラクタが公開されているので、うまくいくpush_back'です。すべてのコンストラクタがprivateであれば、 'emplace_back'も' push_back'も動作しません。 – hvd