home bbs files messages ]

Forums before death by AOL, social media and spammers... "We can't have nice things"

   comp.lang.c++.moderated      Moderated discussion of C++ superhackery      33,346 messages   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]

   Message 33,029 of 33,346   
   Marinca Gheorghe to All   
   Immutable data structures - performance    
   12 May 13 11:31:22   
   
   From: gheorghe.marinca@googlemail.com   
      
   Hi all,   
      
   I recently looked over how a C# library could implement an immutable   
   stack, and came up with this implementation in C++. I wonder here   
   mostly about the overhead of std::shared_pointer(and the missing of a   
   garbage collector that probably could help for this kinds of   
   structures)   
      
   namespace immutable   
   {   
   	template   
   	class stack: public std::enable_shared_from_this>   
   	{   
   	public:   
      
   		typedef std::shared_ptr headPtr;   
   		typedef std::shared_ptr> StackPtr;   
      
   	private:   
   		template  friend struct stackBuilder;   
      
   	public:   
      
   		static StackPtr empty()   
   		{   
   			return std::make_shared>(nullptr, nullptr);   
   		}   
      
   		static StackPtr Create()   
   		{   
   			return empty();   
   		}   
      
   		StackPtr push(const T& head)   
   		{   
   			return std::make_shared>(std::make_shared(head),   
   shared_from_this());   
   		}   
      
   		StackPtr pop()   
   		{   
   			return this->tail;   
   		}   
      
   		headPtr peek()   
   		{   
   			return this->head;   
   		}   
      
   		bool isEmpty()   
   		{   
   			return (this->head == nullptr);   
   		}   
      
   	private:   
   		stack(headPtr head, StackPtr tail): head(head), tail(tail)   
   		{   
   		}   
      
   		stack& operator= (const stack& other);   
      
   	private:   
   		headPtr head;   
   		StackPtr tail;   
   	};   
      
      
   	template    
   	struct stackBuilder: public stack   
   	{   
   		stackBuilder(headPtr head, StackPtr tail): stack(head, tail){}   
   	};   
   }   
      
   An usage would be like this:   
   	auto empty = stack::empty();   
      
   	auto newStack = empty->push(1);   
   	auto stack = newStack;   
   	while(!stack->isEmpty()) //iterate over all elements   
   	{   
   		std::cout << *stack->peek() << "\n";   
   		stack = stack->pop();   
   	}   
      
   How would you think on implementing a general purpose stack in C++ ?   
      
      
   --   
         [ See http://www.gotw.ca/resources/clcm.htm for info about ]   
         [ comp.lang.c++.moderated.    First time posters: Do this! ]   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]


(c) 1994,  bbs@darkrealms.ca