Click here to Skip to main content
15,886,032 members
Articles / Programming Languages / Visual C++ 10.0

Ideas from a Smart Pointer(part 2). size == sizeof(std::shared_ptr)/2

Rate me:
Please Sign up or sign in to vote.
3.50/5 (2 votes)
3 Jun 2012CPOL1 min read 27.6K   103   2  
Embedded ref-counted resource management
#include "stdafx.h"

struct base
{
};

struct der: base
{
	virtual void fff()
	{
	}
};

int main()
{
	using namespace std;

	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF|_CRTDBG_LEAK_CHECK_DF);

	////pointer value can be changed
	der obj;
	base* p = &obj;

	if(p == &obj)
	{
		printf("pointer is equal\n");
	}

	if(unsigned(p) != unsigned(&obj))
	{
		printf("value is not equal\n");
	}
	
	//ref-counted smart pointer for build-in types
	RefNative<int>::Normal n = NativeAlloc<int>(2); //two int
	n[0] = 1;
	n[1] = 2;
	int* pn = n; //smart pointer to raw pointer

	printf("Current ref-count before push_back = %d\n", n.GetRefCount());

	std::vector<RefNative<int>::Normal> vec;
	vec.push_back(n); //auto InterlockedIncrement to make thread-safe. ref-counted pointer can be securely duplicated 

	printf("Current ref-count after push_back = %d\n", n.GetRefCount());

	printf("sizeof(RefNative<int>::Normal) = %d\n", sizeof(RefNative<int>::Normal));

	//alignment support
	RefNative<double, 64>::Aligned na = NativeAllocAligned<double, 64>(1); //allocate one 64 bytes aligned double 
	double* pna = na;
	pna[0] = 3.5;

	printf("sizeof(RefNative<int>::Aligned) = %d\n", sizeof(RefNative<int>::Aligned));

	if(unsigned(pna)%64 == 0)
	{
		puts("it is properly 64 bytes aligned\n");
	}

	return 0;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
China China
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions