想知道我是否可以使用stl智能指针 [英] wondering if I can use stl smart pointers for this

查看:141
本文介绍了想知道我是否可以使用stl智能指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个c ++类如下:

I currently have a c++ class as follows:

template<class T>
class MyQueue {
   T** m_pBuffer;
   unsigned int m_uSize;
   unsigned int m_uPendingCount;
   unsigned int m_uAvailableIdx;
   unsigned int m_uPendingndex;
public:
    MyQueue(): m_pBuffer(NULL), m_uSize(0), m_uPendingCount(0),   m_uAvailableIdx(0),
            m_uPendingndex(0)
    {
    }

    ~MyQueue()
    {
        delete[] m_pBuffer;
    }

    bool Initialize(T *pItems, unsigned int uSize)
    {
        m_uSize = uSize;
        m_uPendingCount = 0;
        m_uAvailableIdx = 0;
        m_uPendingndex = 0;
        m_pBuffer = new T *[m_uSize];
        for (unsigned int i = 0; i < m_uSize; i++)
        {
            m_pBuffer[i] = &pItems[i];
        }
        return true;
    }
};

因此,我有一个指向数组的指针 m_pBuffer 对象,我想知道是否可能用c ++智能指针替换这种做事的方式?我知道我可以做的事情:

So, I have this pointer to arrays m_pBuffer object and I was wondering if it is possible to replace this way of doing things with the c++ smart pointer perhaps? I know I can do things like:

std::unique_ptr<T> buffer(new T[size]);

使用智能指针的向量去吗?这是建议和安全吗?

Is using a vector of smart pointers the way to go? Is this recommended and safe?


根据答案和评论, - 安全缓冲区数组。这里是。请注释。

Based on the answers and the comments, I have tried to make a thread-safe buffer array. Here it is. Please comment.

#ifndef __BUFFER_ARRAY_H__
#define __BUFFER_ARRAY_H__

#include <memory>
#include <vector>
#include <mutex>
#include <thread>
#include "macros.h"

template<class T>
class BufferArray
{
public:
    class BufferArray()
        :num_pending_items(0), pending_index(0), available_index(0)
    {}

    // This method is not thread-safe. 
    // Add an item to our buffer list
    void add(T * buffer)
    {
        buffer_array.push_back(std::unique_ptr<T>(buffer));
    }

    // Returns a naked pointer to an available buffer. Should not be
    // deleted by the caller. 
    T * get_available()
    {
        std::lock_guard<std::mutex> lock(buffer_array_mutex);
        if (num_pending_items == buffer_array.size()) {
            return NULL;
        }       
        T * buffer = buffer_array[available_index].get();
        // Update the indexes.
        available_index = (available_index + 1) % buffer_array.size();
        num_pending_items += 1;
        return buffer;
    }

    T * get_pending()
    {
        std::lock_guard<std::mutex> lock(buffer_array_mutex);
        if (num_pending_items == 0) {
            return NULL;
        }

        T * buffer = buffer_array[pending_index].get();
        pending_index = (pending_index + 1) % buffer_array.size();
        num_pending_items -= 1;
    }


private:
    std::vector<std::unique_ptr<T> >    buffer_array;
    std::mutex                          buffer_array_mutex;
    unsigned int                        num_pending_items;
    unsigned int                        pending_index;
    unsigned int                        available_index;

    // No copy semantics
    BufferArray(const BufferArray &) = delete;
    void operator=(const BufferArray &) = delete;
};

#endif


推荐答案

的智能指针是好主意。它在你的类中是足够安全的 - 提供了自动内存释放。

Vector of smart pointers is good idea. It is safe enough inside your class - automatic memory deallocation is provided.

它不是线程安全的,并且在处理外部内存方面不安全通过简单的指针。

It is not thread-safe though, and it's not safe in regard of handling external memory given to you by simple pointers.

请注意,你当前的实现不会删除析构函数中的pItems内存,所以如果重构后你模仿这个类,你不应该使用智能指针的矢量它们将删除由其指针引用的内存。

Note that you current implementation does not delete pItems memory in destructor, so if after refactoring you mimic this class, you should not use vector of smart pointers as they will delete memory referenced by their pointers.

另一方面,您不能保证noone outside不会释放提供给您的初始化的pItem的内存。如果你想使用智能指针的向量,你应该为这个函数制定合同,清楚地说明你的类声明这个内存等 - 然后你应该重新编写外部代码,调用你的类适应新的合同。
如果你不想改变内存处理,简单指针的向量是要走的路。然而,这段代码非常简单,没有向量的真正好处。

On the other side you cannot garantee that noone outside will not deallocate memory for pItems supplied to your Initialize. IF you want to use vector of smart pointers, you should formulate contract for this function that clearly states that your class claims this memory etc. - and then you should rework outside code that calls your class to fit into new contract. If you don't want to change memory handling, vector of simple pointers is the way to go. Nevertheless, this piece of code is so simple, that there is no real benefit of vector.

请注意,这里的开销是为每个缓冲区创建智能指针类,矢量类。重新分配向量可能占用更多的内存,并发生没有你的直接控制。

Note that overhead here is creation of smart pointer class for each buffer and creation of vector class. Reallocation of vector can take up more memory and happens without your direct control.

这篇关于想知道我是否可以使用stl智能指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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