C ++分配对象的存储,而不初始化它? [英] C++ Allocate Storage for Object without Initializing it?

查看:106
本文介绍了C ++分配对象的存储,而不初始化它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个接受的习语为现场分配对象的后备存储,但不初始化它?这是我天真的解决方案:

Is there an accepted idiom for allocating the backing store for an object in-place but not initializing it? Here's my naive solution:

#include <utility>

template<typename T> 
union Slot {
    T inst;

    Slot() {}
    ~Slot() {}

    template<typename... Args>
    T* init(Args&&... args) { return new(&inst) T(std::forward<Args>(args) ...); }
    void release() { inst.~T(); }
};

我的直接用例是一个对象池,但也更有用。 p>

My immediate use case is for an object pool, but it would also be more generally useful.

推荐答案

在C ++ 11中, a href =http://en.cppreference.com/w/cpp/types/aligned_storage =nofollow> see also ):

In C++11 you can use std::aligned_storage (see also ):

template<typename T> 
struct Slot {
    typename std::aligned_storage<sizeof(T)>::type _storage;

    Slot() {}
    ~Slot() { 
       // check if destroyed!
       ...
    }

    template<typename... Args>
    T* init(Args&&... args) { 
        return new(address()) T(std::forward<Args>(args) ...); 
    }

    void release() { (*address()).~T(); }

    T* address()  {
        return static_cast<T*>(static_cast<void*>(&_storage));
    }
};

这篇关于C ++分配对象的存储,而不初始化它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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