الفريق العربي للبرمجةأرشيف المنتديات · 2000 – 2023
نسخة أرشيفية للقراءة فقط — التسجيل والمشاركة مغلقان، والمحتوى محفوظ كما كان.

custom allocator

بدأه C++er في 6 أغسطس 2011 · 1 رد · 417 مشاهدة · في لغة C و ++C
مشاركة: واتساب X فيسبوك تيليجرام
#1 صاحب الموضوع

قمت بكتابة الـ allocator التالي:

// static_allocator.h

#include <memory>
using std::allocator;

template <typename t, uint32 length>
class static_allocator : public allocator<t>
{
public:
	typedef t value_type;
	typedef t *pointer;
	typedef t& reference;
	typedef const t *const_pointer;
	typedef const t& const_reference;

	typedef unsigned size_type;
	typedef int  difference_type;

private:
	static t _array[length];

public:
	template<class u> struct rebind
	{ typedef allocator<u> other; };

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

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

	static_allocator() {}

	static_allocator(const static_allocator&) {}

	template<class Other>
	static_allocator(const allocator<Other>&) {}

	template<class Other>
	static_allocator& operator=(const allocator<Other>&) { return (*this); }

	void deallocate(pointer p, size_type) {}

	pointer allocate(size_type count) { return _array; }

	pointer allocate(size_type count, const void*) { return _array; }

	void construct(pointer p, const achar& v) {}

	void destroy(pointer p) {}

	size_type max_size() const { return length; }
};

الهدف من هذا الـ allocator هو وجود مساحه ثابته يتم التعامل معها من قبله - static، المشكله ان البرنامج يتم ترجمته بنجاح و لكن عند التنفيذ يتم إستخدام دوال الفئه allocator و ليس static_allocator الخاصه بي و لا اعرف لماذا؟ إليكم مثال:

#include <vector>
#include "static_allocator.h"
using std::vector;

int32 main()
{
	typedef static_allocator<int, 8> static_int;

	vector< int, static_int> v;

	for (int i=0; i<10; i++)
		v.push_back(i);
}

المفترض عند التنفيذ إذا تم استخدام static_allocator ان تحدث مشكله لأن عدد عناصره هي 8 و الحلقه تقوم بإضافة 10 عناصر.

و الله ولي التوفيق

مدونتي: C++ Tips and Tricks

#2

تم حل المشكله،

المشكله كانت فى الـ copy constructor حيث بشكله الحالي:

        template<class Other>
        static_allocator(const allocator<Other>&)

و المفترض ان يكون

        template<class Other>
        static_allocator(const static_allocator<Other>&)

مشكلة نسخ اضاعت وقت كبير :sleep:

و الله ولي التوفيق

مدونتي: C++ Tips and Tricks

مواضيع مشابهة