【Poco】Poco::AutoPtr的例子

#include "../tmain.hpp"

class TestObj
{
public:
	TestObj(): _rc(1)
	{
		// PRINT_DEBUG("TestObj Construct" << " " << this);
		++_count;
	}
	// AutoPtr的复制构造函数有调用duplicate函数
	void duplicate()
	{
		// PRINT_DEBUG("duplicate" << " " << this);
		++_rc;
	}
	// AutoPtr中的析造函数调用release函数
	void release()
	{
		// PRINT_DEBUG("release" << " " << this);
		if (--_rc == 0) delete this;
	}
	int rc() const {return _rc;}
	static int count() {return _count;}
protected:
	virtual ~TestObj()
	{
		// PRINT_DEBUG("TestObj Deconstruct");
		--_count;
	}
private:
	int _rc;
	static int _count;
};
int TestObj::_count = 0;

void test_ap()
{
	{
		Poco::AutoPtr<TestObj> ptr = new TestObj;
		assert (ptr->rc() == 1);
		Poco::AutoPtr<TestObj> ptr2 = ptr;
		assert (ptr->rc() == 2);
		ptr2 = new TestObj;
		assert (ptr->rc() == 1);
		Poco::AutoPtr<TestObj> ptr3;
		ptr3 = ptr2;
		assert (ptr2->rc() == 2);
		ptr3 = new TestObj;
		assert (ptr2->rc() == 1);
		ptr3 = ptr2;
		assert (ptr2->rc() == 2);
		assert (TestObj::count() > 0);
	}
	assert (TestObj::count() == 0);
}

void test_ap_ops()
{
	Poco::AutoPtr<TestObj> ptr1;
	TestObj* pTO1 = new TestObj;
	TestObj* pTO2 = new TestObj;
	if (pTO2 < pTO1)
	{
		TestObj* pTmp = pTO1;
		pTO1 = pTO2;
		pTO2 = pTmp;
	}
	assert (pTO1 < pTO2);
	ptr1 = pTO1;
	Poco::AutoPtr<TestObj> ptr2 = pTO2;
	Poco::AutoPtr<TestObj> ptr3 = ptr1;
	Poco::AutoPtr<TestObj> ptr4;
	assert (ptr1.get() == pTO1);
	assert (ptr1 == pTO1);
	assert (ptr2.get() == pTO2);
	assert (ptr2 == pTO2);
	assert (ptr3.get() == pTO1);
	assert (ptr3 == pTO1);
	PRINT_DEBUG(ptr1->count());
	PRINT_DEBUG(ptr1->rc());
	PRINT_DEBUG(ptr2->count());
	PRINT_DEBUG(ptr2->rc());

	assert (ptr1 == pTO1);
	assert (ptr1 != pTO2);
	assert (ptr1 < pTO2);
	assert (ptr1 <= pTO2);
	assert (ptr2 > pTO1);
	assert (ptr2 >= pTO1);

	assert (ptr1 == ptr3);
	assert (ptr1 != ptr2);
	assert (ptr1 < ptr2);
	assert (ptr1 <= ptr2);
	assert (ptr2 > ptr1);
	assert (ptr2 >= ptr1);

	ptr1 = pTO1;
	ptr2 = pTO2;
	ptr1.swap(ptr2);
	assert (ptr2.get() == pTO1);
	assert (ptr1.get() == pTO2);

	try
	{
		assert (ptr4->rc() > 0);
	}
	catch (...)
	{
	}

	assert (!(ptr4 == ptr1));
	assert (!(ptr4 == ptr2));
	assert (ptr4 != ptr1);
	assert (ptr4 != ptr2);

	ptr4 = ptr2;
	assert (ptr4 == ptr2);
	assert (!(ptr4 != ptr2));

	assert (!(!ptr1));
	ptr1 = 0;
	assert (!ptr1);
}

你可能感兴趣的:(【Poco】Poco::AutoPtr的例子)