5

new的对象可以直接用析构函数代替delete删除吗?

 3 years ago
source link: https://www.zhihu.com/question/466944998/answer/1957874795
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
new的对象可以直接用析构函数代替delete删除吗? - 知乎
登录后你可以
不限量看优质回答私信答主深度交流精彩内容一键收藏
C++程序猿, 公众号:高级开发者

如果你是placement new,那是可以的。

template<class T, std::size_t N>
class static_vector
{
    // properly aligned uninitialized storage for N T's
    std::aligned_storage_t<sizeof(T), alignof(T)> data[N];
    std::size_t m_size = 0;
 
public:
    // Create an object in aligned storage
    template<typename ...Args> void emplace_back(Args&&... args) 
    {
        if( m_size >= N ) // possible error handling
            throw std::bad_alloc{};
 
        // construct value in memory of aligned storage
        // using inplace operator new
        new(&data[m_size]) T(std::forward<Args>(args)...);
        ++m_size;
    }
 
    // Access an object in aligned storage
    const T& operator[](std::size_t pos) const 
    {
        return *reinterpret_cast<const T*>(&data[pos]);
    }
 
    // Delete objects from aligned storage
    ~static_vector() 
    {
        for(std::size_t pos = 0; pos < m_size; ++pos) {
            reinterpret_cast<T*>(&data[pos])->~T();
        }
    }
};

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK