我可以在Apache模块中安全地使用Boost和/或C ++库吗?

时间:2012-07-22 13:38:41

标签: c++ apache boost apache-modules

在我使用C ++构建的Apache模块中,我在尝试为模块提供功能时使用了字符串,向量和相关内容。

我担心的是我没有使用Apache内存池,程序会在整个过程中出现段错误,但与此同时我遇到某些任务有困难:

static void parseSTR(char *input, const char *sep, int &count, apr_table_t *&values, apr_pool_t *mp)
{
    char *part, *next;

    if (isStrNull(input)) 
        return;

    count = 1;

    part = apr_strtok(input, sep, &next);

    while (part) {
        apr_table_set(values, apr_itoa(mp, count), part);

        part = apr_strtok(NULL, sep, &next);

        count++;
    }
}

我使用分隔的字符串解析器来解析URL和域名。当然,有一种更有效的方式来提供此功能。我使用apr_table结构来包含每个部分,我知道我可以使用apr_array_header,但是....

所以我想知道:

  1. 我可以使用Boost安全地提供缺少的功能吗?
  2. 我是否会遇到内存冲突,因为我没有使用池内存?
  3. 对于释放自己内存的字符串,向量等,这是一个等待的问题吗?
  4. 我确实在搜索此问题,但其他问题似乎并不相同。

2 个答案:

答案 0 :(得分:2)

使用Boost应该是安全的,这取决于你正在使用的特定部分,但是要对其安全性做出任何明确的调用。

至于内存管理,您可以编写自己的std :: allocator实现,它使用Apache / APR的内存分配。然后,您可以将此分配器作为模板参数传递给您正在使用的STL容器(通常第二个模板参数)。

至于Boost的智能指针(如果你正在使用它们),他们可以(在构造时)给出一个函数指针作为实现内存释放的参数(作为delete的替代)。 / p>

E.g。像这样的分配器可以帮到你:

#include <stdexcept>

template <typename T>
class apr_allocator
{
    public:
        typedef size_t    size_type;
        typedef ptrdiff_t difference_type;
        typedef T*        pointer;
        typedef const T*  const_pointer;
        typedef T&        reference;
        typedef const T&  const_reference;
        typedef T         value_type;

        template<typename U>
        struct rebind
        { typedef apr_allocator<U> other; };

        pointer allocate(size_type n, const void* = 0)
        {
            pointer new_mem = apr_do_whatever_is_necessary_to_allocate(n * sizeof(value_type));
            if (!new_mem)
                throw std::bad_alloc();
            return new_mem;
        }

        void deallocate(pointer p, size_type n)
        {
            apr_release_memory(p, n);
        }

        pointer address(reference r) const
        {
            return &r;
        }

        const_pointer address(const_reference r) const
        {
            return &r;
        }

        size_type max_size() const
        {
            // Largest amount of elements T that can meaningfully be allocated
            return 1337;
        }

        void construct(pointer p, const_reference val)
        {
            new ((void *)p) value_type(val);
        }

        void destroy(pointer p)
        {
            p->~T();
        }
};

template <typename T>
inline bool operator==(const apr_allocator<T>& a, const new_allocator<T>& b)
{
    if (&a == &b)
        return true;
    if (/* a can deallocate elements created with b and vice-versa */)
        return true;
    return false;
}

template <typename T>
inline bool operator!=(const apr_allocator<T>& a, const apr_allocator<T>& b)
{
    return !(a == b);
}

另请注意,如果您的分配器需要内部状态(例如对特定内存池的引用),则必须确保分配器是可复制构建的。此外,必须是默认构造的(尽管您可以将预先构造的实例作为参数传递给STL容器的构造函数)。

答案 1 :(得分:0)

我们在Windows上的Apache中大量使用C ++和Boost,我们没有看到与使用new或类似C ++主题相关的任何问题。