### Boost Pointer Map Iterator Example (Before Boost v1.34) Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/index Demonstrates the iteration pattern for `boost::ptr_map` before version 1.34, accessing key and value through the iterator. ```C++ for( boost::ptr_map::iterator i = m.begin(), e = m.end(); i != e; ++i ) { std::cout << "key:" << i.key(); std::cout << "value:" << *i; i->foo(); // call T::foo() } ``` -------------------------------- ### Create and Populate Boost Pointer Container Views Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/test/view_example Demonstrates initializing a 'ptr_vector' with a 'view_clone_allocator' and populating it with data from a standard vector. The 'insert' function copies elements, creating clones within the view container. This setup allows multiple sorted views of the same underlying data. ```cpp #include #include #include // For 'binary_fnuction' #include // For 'rand()' #include // For 'std::sort()' #include // For 'std::cout' using namespace std; // // Our big container is a standard vector // typedef std::vector vector_type; // // Now we define our view type by adding a second template argument. // The 'view_clone_manager' will implements Cloning by taking address // of objects. // // Notice the first template argument is 'photon' and not // 'const photon' to allow the view container write access. // typedef boost::ptr_vector view_type; // // This function inserts "Clones" into the // the view. // // We need to pass the first argument // as a non-const reference to be able to store // 'T*' instead of 'const T*' objects. Alternatively, // We might change the declaration of the 'view_type' // to // typedef boost::ptr_vector // view_type; ^^^^^^ // void insert( vector_type& from, view_type& to ) { to.insert( to.end(), from.begin(), from.end() ); } int main() { enum { sz = 10, count = 500 }; // // First we create the main container and two views // std::vector photons; view_type color_view; view_type direction_view; // // Then we fill the main container with some random data // for( int i = 0; i != sz; ++i ) { photons.push_back( vector_type() ); for( int j = 0; j != count; ++j ) photons[i].push_back( photon() ); } // // Then we create the two views. // for( int i = 0; i != sz; ++i ) { insert( photons[i], color_view ); insert( photons[i], direction_view ); } // // First we sort the original photons, using one of // the view classes. This may sound trivial, but consider that // the objects are scatered all around 'sz' different vectors; // the view makes them act as one big vector. // std::sort( color_view.begin(), color_view.end(), sort_by_power() ); // // And now we can sort the views themselves. Notice how // we switch to different iterators and different predicates: // color_view.sort( sort_by_color() ); direction_view.sort( sort_by_direction() ); return 0; } ``` -------------------------------- ### Manage Animals in a Farm Using ptr_deque Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/doc/examples Demonstrates the 'farm' class, which uses 'boost::ptr_deque' to manage a collection of animal objects. It supports adding animals, iterating through them, and cloning animals from a range during construction. Ownership is managed by the container. ```C++ // // Then we, of course, need a place to put all // those animals. // class farm { // // This is where the smart containers are handy // typedef boost::ptr_deque barn_type; barn_type barn; // // A convenience typedef for the compiler-appropriate // smart pointer used to manage barns // typedef _compatible-smart-ptr_ raii_ptr; // // An error type // struct farm_trouble : public std::exception { }; public: // // We would like to make it possible to // iterate over the animals in the farm // typedef barn_type::iterator animal_iterator; // // We also need to count the farm's size... // typedef barn_type::size_type size_type; // // And we also want to transfer an animal // safely around. The easiest way to think // about '::auto_type' is to imagine a simplified // 'std::auto_ptr' ... this means you can expect // // T* operator->() // T* release() // deleting destructor // // but not more. // typedef barn_type::auto_type animal_transport; // // Create an empty farm. // farm() { } // Constructor // // We need a constructor that can make a new // farm by cloning a range of animals. // farm( animal_iterator begin, animal_iterator end ) : // // Objects are always cloned before insertion // unless we explicitly add a pointer or // use 'release()'. Therefore we actually // clone all animals in the range // barn( begin, end ) { } // Constructor with range cloning // // ... so we need some other function too // animal_iterator begin() { return barn.begin(); } animal_iterator end() { return barn.end(); } // // Here it is quite ok to have an 'animal*' argument. // The smart container will handle all ownership // issues. // void buy_animal( animal* a ) { barn.push_back( a ); } // // The farm can also be in economical trouble and // therefore be in the need to sell animals. // // Note: The code for selling animals is not provided in this snippet. }; ``` -------------------------------- ### Main Function: Farm Operations Simulation Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/doc/examples The 'main' function simulates the lifecycle and operations of a 'farm' object. It demonstrates creating farms, buying animals, copying farms, selling and buying back animals, and transferring all animals from one farm to another, verifying the farm sizes at each step. ```C++ int main() { // // First we make a farm // farm animal_farm; BOOST_ASSERT( animal_farm.size() == 0u ); animal_farm.buy_animal( new pig("Betty") ); animal_farm.buy_animal( new pig("Benny") ); animal_farm.buy_animal( new pig("Jeltzin") ); animal_farm.buy_animal( new cow("Hanz") ); animal_farm.buy_animal( new cow("Mary") ); animal_farm.buy_animal( new cow("Frederik") ); BOOST_ASSERT( animal_farm.size() == 6u ); // // Then we make another farm...it will actually contain // a clone of the other farm. // farm new_farm( animal_farm.begin(), animal_farm.end() ); BOOST_ASSERT( new_farm.size() == 6u ); // // Is it really clones in the new farm? // BOOST_ASSERT( new_farm.begin()->name() == "Betty" ); // // Then we search for an animal, Mary (the Crown Princess of Denmark), // because we would like to buy her ... // typedef farm::animal_iterator iterator; iterator to_sell; for( iterator i = animal_farm.begin(), end = animal_farm.end(); i != end; ++i ) { if( i->name() == "Mary" ) { to_sell = i; break; } } farm::animal_transport mary = animal_farm.sell_animal( to_sell ); if( mary->speak() == muuuh ) // // Great, Mary is a cow, and she may live longer // new_farm.buy_animal( mary.release() ); else // // Then the animal would be destroyed (!) // when we go out of scope. // ; // // Now we can observe some changes to the two farms... // BOOST_ASSERT( animal_farm.size() == 5u ); BOOST_ASSERT( new_farm.size() == 7u ); // // The new farm has however underestimated how much // it cost to feed Mary and its owner is forced to sell the farm... // animal_farm.buy_farm( new_farm.sell_farm() ); BOOST_ASSERT( new_farm.size() == 0u ); BOOST_ASSERT( animal_farm.size() == 12u ); } ``` -------------------------------- ### Boost Pointer Container Copy and Assignment Example (C++) Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/doc/ptr_container Demonstrates how Boost.Pointer Container classes are now copy-constructible and assignable, allowing for derived-to-base class conversions. This feature was introduced in Boost v. 1.34.*. ```cpp boost::ptr_vector derived = ...; boost::ptr_vector base( derived ); base = derived; ``` -------------------------------- ### Manage copy semantics in Boost pointer containers Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/doc/examples Illustrates the difference between deep copying, shallow copying/ownership transfer, and release operations in Boost pointer containers. The clone() method performs expensive deep copies, while release() transfers ownership at lower cost. ```cpp ptr_vector vec1; ... ptr_vector vec2( vec1.clone() ); // deep copy objects of 'vec1' and use them to construct 'vec2', could be very expensive vec2 = vec1.release(); // give up ownership of pointers in 'vec1' and pass the ownership to 'vec2', rather cheap vec2.release(); // give up ownership; the objects will be deallocated if not assigned to another container vec1 = vec2; // deep copy objects of 'vec2' and assign them to 'vec1', could be very expensive ptr_vector vec3( vec1 ); // deep copy objects of 'vec1', could be very expensive ``` -------------------------------- ### Boost Unit Test Suite Initialization in C++ Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/test/tree_test Sets up a Boost unit test suite for pointer container functionalities. It includes the necessary header for Boost unit testing and defines a test suite named 'Pointer Container Test Suite'. A specific test case, 'test_tree', is added to this suite. ```cpp #include using boost::unit_test::test_suite; test_suite* init_unit_test_suite( int argc, char* argv[] ) { test_suite* test = BOOST_TEST_SUITE( "Pointer Container Test Suite" ); test->add( BOOST_TEST_CASE( &test_tree ) ); return test; } ``` -------------------------------- ### Boost Pointer Map Iterator Example (After Boost v1.34) Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/index Illustrates the updated iteration pattern for `boost::ptr_map` from version 1.34 onwards, where iterators mimic `std::map` behavior. ```C++ for( boost::ptr_map::iterator i = m.begin(), e = m.end(); i != e; ++i ) { std::cout << "key:" << i->first; std::cout << "value:" << *i->second; i->second->foo(); // call T::foo() } ``` -------------------------------- ### Defining operator< for Animal Sorting Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/doc/tutorial Provides an example of how to define the `operator<()` for the `animal` class, enabling `boost::ptr_set` to sort animals based on their names. ```cpp inline bool operator<( const animal& l, const animal& r ) { return l.name() < r.name(); } ``` -------------------------------- ### Tree Structure Initialization and Manipulation in C++ Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/test/tree_test Demonstrates the creation and population of a tree structure using Boost Pointer Container library. It shows how to add inner nodes and leaf nodes with different data types, release ownership, and verify the tree's size after additions. The code also includes writing the tree to standard output and finding specific elements. ```cpp tree root; BOOST_CHECK_EQUAL( root.size(), 1u ); inner_node node1( "node 1" ); node1.add_child( new leaf( "leaf 1" ) ); node1.add_child( new leaf( 42 ) ); inner_node node2( "node 2" ); node2.add_child( new leaf( 42.0f ) ); node2.add_child( new leaf( "leaf 4" ) ); root.add_child( node1.release() ); BOOST_CHECK_EQUAL( root.size(), 4u ); root.add_child( node2.release() ); root.add_child( new inner_node( "node 3" ) ); BOOST_CHECK_EQUAL( root.size(), 8u ); root.add_child( new leaf( "leaf 5" ) ); BOOST_CHECK_EQUAL( root.size(), 9u ); root.write_tree( cout ); tree::iterator a_leaf = root.find( "42" ); BOOST_CHECK_EQUAL( a_leaf->description(), "42" ); leaf& the_leaf = dynamic_cast< leaf& >( *a_leaf ); the_leaf.set_data( 2*42 ); BOOST_CHECK_EQUAL( a_leaf->description(), "84" ); ``` -------------------------------- ### Farm Class Definition and Animal Management Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/doc/examples Defines the 'farm' class with methods for managing animals. It includes functions to sell individual animals, retrieve the farm size, sell the entire farm, and buy another farm's animals. The 'sell_animal' method releases an animal, and 'buy_farm' transfers animals from another farm, ensuring atomicity. ```C++ animal_transport sell_animal( animal_iterator to_sell ) { if( to_sell == end() ) throw farm_trouble(); // // Here we remove the animal from the barn, // but the animal is not deleted yet...it's // up to the buyer to decide what // to do with it. // return barn.release( to_sell ); } // // How big a farm do we have? // size_type size() const { return barn.size(); } // // If things are bad, we might choose to sell all animals :-( // raii_ptr sell_farm() { return barn.release(); } // // However, if things are good, we might buy somebody // else's farm :-) // void buy_farm( raii_ptr other ) { // // This line inserts all the animals from 'other' // and is guaranteed either to succeed or to have no // effect // barn.transfer( barn.end(), // insert new animals at the end *other ); // we want to transfer all animals, // so we use the whole container as argument // // You might think you would have to do // // other.release(); // // but '*other' is empty and can go out of scope as it wants // BOOST_ASSERT( other->empty() ); } }; // class 'farm'. ``` -------------------------------- ### Define Polymorphic Animal Hierarchy with Cloning Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/doc/examples Defines a base 'animal' class with virtual methods for speaking and cloning, ensuring proper ownership management. Derived classes 'cow' and 'pig' implement these methods. The base class is noncopyable but supports cloning. ```C++ // // Boost.Pointer Container // // Copyright Thorsten Ottosen 2003-2005. Use, modification and // distribution is subject to the Boost Software License, Version // 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // For more information, see http://www.boost.org/libs/ptr_container/ // // // This example is intended to get you started. // Notice how the smart container // // 1. takes ownership of objects // 2. transfers ownership // 3. applies indirection to iterators // 4. clones objects from other smart containers // // // First we select which container to use. // #include // // we need these later in the example // #include #include #include // // Then we define a small polymorphic class // hierarchy. // class animal : boost::noncopyable { virtual std::string do_speak() const = 0; std::string name_; protected: // // Animals cannot be copied... // animal( const animal& r ) : name_( r.name_ ) { } // Copy constructor void operator=( const animal& ); // Assignment operator private: // // ...but due to advances in genetics, we can clone them! // virtual animal* do_clone() const = 0; public: animal( const std::string& name ) : name_(name) { } // Constructor virtual ~animal() throw() { } // Virtual destructor std::string speak() const { return do_speak(); } std::string name() const { return name_; } animal* clone() const { return do_clone(); } }; // // An animal is still not Clonable. We need this last hook. // // Notice that we pass the animal by const reference // and return by pointer. // animal* new_clone( const animal& a ) { return a.clone(); } // // We do not need to define 'delete_clone()' since // since the default is to call the default 'operator delete()'. // const std::string muuuh = "Muuuh!"; const std::string oiink = "Oiiink"; class cow : public animal { virtual std::string do_speak() const { return muuuh; } virtual animal* do_clone() const { return new cow( *this ); } public: cow( const std::string& name ) : animal(name) { } // Constructor }; class pig : public animal { virtual std::string do_speak() const { return oiink; } virtual animal* do_clone() const { return new pig( *this ); } public: pig( const std::string& name ) : animal(name) { } // Constructor }; ``` -------------------------------- ### Implement Tree Operations using ptr_vector - C++ Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/test/tree_test Provides the implementation for the `tree` class methods, including adding and removing children, writing the tree structure to an output stream, calculating the total size of the tree, accessing children by index, iterating through children, and finding nodes by description. These operations leverage `boost::ptr_vector` for efficient management. ```cpp ///////////////////////////////////////////////////////////////////////// // tree implementation ///////////////////////////////////////////////////////////////////////// inline void tree::add_child( node* n ) { nodes.push_back( n ); } inline void tree::remove( iterator n ) { BOOST_ASSERT( n != nodes.end() ); nodes.erase( n ); } void tree::write_tree( ostream& os ) const { for( const_iterator i = nodes.begin(), e = nodes.end(); i != e; ++i ) { i->write_value( os ); if( const inner_node* p = dynamic_cast( &*i ) ) p->write_tree( os ); } } size_t tree::size() const { size_t res = 1; for( const_iterator i = nodes.begin(), e = nodes.end(); i != e; ++i ) { res += i->node_size(); } return res; } inline node& tree::child( size_t idx ) { return nodes[idx]; } inline const node& tree::child( size_t idx ) const { return nodes[idx]; } inline tree::iterator tree::child_begin() { return nodes.begin(); } inline tree::const_iterator tree::child_begin() const { return nodes.begin(); } inline tree::iterator tree::child_end() { return nodes.end(); } inline tree::const_iterator tree::child_end() const { return nodes.end(); } tree::iterator tree::find( const string& match ) { for( iterator i = nodes.begin(), e = nodes.end(); i != e; ++i ) { if( i->description() == match ) return i; if( inner_node* p = dynamic_cast( &*i ) ) { iterator j = p->find( match ); if( j != p->child_end() ) return j; } } return child_end(); } ``` -------------------------------- ### Farm Class Definition and Operations Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/test/tut1 Defines the 'farm' class, which manages a collection of animals using Boost.Pointer Container. It supports operations like buying animals, releasing animals, getting the farm size, selling the entire farm, and buying another farm. ```cpp class farm { // ... (members not shown) public: // ... void buy_animal(animal* a) { barn.push_back(a); } animal_transport release_animal( animal_iterator i ) { return barn.release( i ); } size_type size() const { return barn.size(); } raii_ptr sell_farm() { return barn.release(); } void buy_farm( raii_ptr other ) { barn.transfer( barn.end(), *other ); BOOST_ASSERT( other->empty() ); } }; ``` -------------------------------- ### Test Tree Structure with Polymorphic Nodes - C++ Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/test/tree_test Contains a test function `test_tree` which would typically instantiate and manipulate the `tree` and `node` structures to verify their functionality. This snippet serves as a placeholder for testing the tree implementation. ```cpp ///////////////////////////////////////////////////////////////////////// // test case ///////////////////////////////////////////////////////////////////////// void test_tree() { ``` -------------------------------- ### ptr_multimap Key Insertion Error Example Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/doc/tutorial Highlights an incorrect way to insert elements into `boost::ptr_multimap` by using a temporary string literal as the key, which can lead to compilation errors due to exception-safety concerns. ```cpp zoo.insert( "bobo", // this is bad, but you get compile error new monkey("bobo") ); ``` -------------------------------- ### Make non-copyable types Cloneable for Boost containers Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/doc/examples Demonstrates how to enable cloning support for non-copyable classes by implementing a new_clone() function that uses argument-dependent lookup (ADL). This allows non-copyable types to work with Boost pointer containers that require cloneability. ```cpp // a class that has no normal copy semantics class X : boost::noncopyable { public: X* clone() const; ... }; // this will be found by the library by argument dependent lookup (ADL) X* new_clone( const X& x ) { return x.clone(); } // we can now use the interface that requires cloneability ptr_vector vec1, vec2; ... vec2 = vec1.clone(); // 'clone()' requires cloning vec2.insert( vec2.end(), vec1.begin(), vec1.end() ); // inserting always means inserting clones ``` -------------------------------- ### Transfer pointers between different Boost pointer containers Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/doc/examples Shows how to transfer elements between different Boost pointer container types (ptr_list, ptr_vector, ptr_deque) using the transfer() method without cloning. Supports transferring derived class pointers to base class containers. ```cpp ptr_list list; ptr_vector vec; ... // // note: no cloning happens in these examples // list.transfer( list.begin(), vec.begin(), vec ); // make the first element of 'vec' the first element of 'list' vec.transfer( vec.end(), list.begin(), list.end(), list ); // put all the lists element into the vector ``` -------------------------------- ### Insert cloned objects with ownership transfer in Boost containers Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/doc/examples Shows best practices for inserting objects into Boost pointer containers. Objects are cloned before insertion, and the container takes ownership of inserted pointers. Always pass pointers directly to the container to avoid memory leaks. ```cpp class X { ... }; // assume 'X' is Cloneable X x; // and 'X' can be stack-allocated ptr_list list; list.push_back( new_clone( x ) ); // insert a clone list.push_back( new X ); // always give the pointer directly to the container to avoid leaks list.push_back( &x ); // don't do this!!! std::auto_ptr p( new X ); list.push_back( p ); // give up ownership BOOST_ASSERT( p.get() == 0 ); ``` -------------------------------- ### Get Base Container Reference Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/doc/reversible_ptr_container Returns a reference to the underlying (wrapped) container. Provides both non-const and const versions. ```cpp VoidPtrContainer& base(); ``` ```cpp const VoidPtrContainer& base() const; ``` -------------------------------- ### Boost Unit Test Suite Initialization Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/test/simple_test Sets up a Boost unit test suite named 'Pointer Container Test Suite' and adds the 'simple_test' function as a test case. This is the standard way to integrate tests using the Boost.Test framework. ```C++ #include using boost::unit_test::test_suite; test_suite* init_unit_test_suite( int argc, char* argv[] ) { test_suite* test = BOOST_TEST_SUITE( "Pointer Container Test Suite" ); test->add( BOOST_TEST_CASE( &simple_test ) ); return test; } ``` -------------------------------- ### Accessing Wrapped Container (C++) Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/index Provides functions to get direct access to the underlying container within a Boost.Pointer Container. This is useful for extending functionality or when direct manipulation is required. ```C++ VoidPtrContainer& base(); const VoidPtrContainer& base() const; ``` -------------------------------- ### Checking for Null in ptr_vector Iterator Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/doc/tutorial Provides an example of iterating through a `boost::ptr_vector` containing nullable objects and checking if each element is null using `boost::is_null` before accessing its members. ```cpp for( animals_type::iterator i = animals.begin(); i != animals.end(); ++i ) { if( !boost::is_null(i) ) // always check for validity i->eat(); } ``` -------------------------------- ### Smart Pointer Compatibility (C++) Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/index Explains the integration with `std::unique_ptr` alongside `std::auto_ptr` starting from Boost v. 1.67.0. This provides conditional interfaces based on C++ standards and compiler support. ```C++ _compatible-smart-ptr_ ``` -------------------------------- ### Main Function: Farm Simulation and Operations Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/test/tut1 The main function orchestrates a simulation involving multiple 'farm' objects. It demonstrates creating farms, populating them with animals (pigs and cows), transferring animals between farms, and merging entire farms. ```cpp int main() { farm animal_farm; BOOST_ASSERT( animal_farm.size() == 0u ); animal_farm.buy_animal( new pig("Betty") ); animal_farm.buy_animal( new pig("Benny") ); animal_farm.buy_animal( new pig("Jeltzin") ); animal_farm.buy_animal( new cow("Hanz") ); animal_farm.buy_animal( new cow("Mary") ); animal_farm.buy_animal( new cow("Frederik") ); BOOST_ASSERT( animal_farm.size() == 6u ); farm new_farm( animal_farm.begin(), animal_farm.end() ); BOOST_ASSERT( new_farm.size() == 6u ); typedef farm::animal_iterator iterator; iterator to_sell; for( iterator i = animal_farm.begin(), end = animal_farm.end(); i != end; ++i ) { if( i->name() == "Mary" ) { to_sell = i; break; } } farm::animal_transport mary = animal_farm.sell_animal( to_sell ); if( mary->speak() == muuuh ) new_farm.buy_animal( mary.release() ); else ; BOOST_ASSERT( animal_farm.size() == 5u ); BOOST_ASSERT( new_farm.size() == 7u ); animal_farm.buy_farm( new_farm.sell_farm() ); BOOST_ASSERT( new_farm.size() == 0u ); BOOST_ASSERT( animal_farm.size() == 12u ); } ``` -------------------------------- ### Cloning a Complete ptr_list Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/doc/tutorial Demonstrates how to clone an entire `boost::ptr_list` using its `clone()` method, creating a new list with independent copies of the elements. ```cpp zoo_type yet_another_zoo = zoo.clone(); ``` -------------------------------- ### Efficient Container Return: `clone()` and `release()` in Boost Pointer Container Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/doc/conventions Explains the `clone()` and `release()` member functions, which provide efficient ways to return Boost pointer containers from functions. `clone()` returns a copy of the container, while `release()` transfers ownership of the container itself. Both return a compatible smart pointer, minimizing overhead to a single heap allocation and a swap operation. ```cpp #include struct animal {}; // Function returning a container by value (efficiently) boost::ptr_vector create_animals() { boost::ptr_vector vec; vec.push_back(new animal()); // Option 1: Return by clone (creates a copy) // return vec.clone(); // Option 2: Return by release (transfers ownership) return vec.release(); } int main() { auto animals = create_animals(); return 0; } ``` -------------------------------- ### Container Copy and Assignment (C++) Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/index Demonstrates how Boost.Pointer Containers, specifically ptr_vector, now support copy construction and assignment, including derived-to-base conversions. This allows for flexible object management. ```C++ boost::ptr_vector derived = ...; boost::ptr_vector base( derived ); base = derived; ``` -------------------------------- ### Resizing Sequence Containers (C++) Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/index Shows how to resize sequence-based Boost.Pointer Containers. The `resize` function can take a size and an optional pointer to a cloneable object for initializing new elements. ```C++ void resize( size_type size ); void resize( size_type size, T* to_clone ); ``` -------------------------------- ### Boost C++ ptr_multiset Class Synopsis Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/doc/ptr_multiset This C++ code snippet provides the synopsis for the `boost::ptr_multiset` class. It details the template parameters, base class, and namespace. ```cpp namespace boost { template < class Key, class Compare = std::less, class CloneAllocator = heap_clone_allocator, class Allocator = std::allocator > class ptr_multiset : public ptr_multiset_adapter < Key, std::multiset,Allocator>, CloneAllocator > { // see references }; // class 'ptr_multiset' } // namespace 'boost' ``` -------------------------------- ### Transfer ownership of single elements from Boost ptr_deque Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/doc/examples Demonstrates how to extract and transfer ownership of individual elements from Boost pointer containers using pop_back(), pop_front(), and release() methods. The auto_type typedef represents the container's pointer ownership type. ```cpp ptr_deque deq; typedef ptr_deque::auto_type auto_type; // ... fill the container somehow auto_type ptr = deq.pop_back(); // remove back element from container and give up ownership auto_type ptr2 = deq.release( deq.begin() + 2 ); // use an iterator to determine the element to release ptr = deq.pop_front(); // supported for 'ptr_list' and 'ptr_deque' deq.push_back( ptr.release() ); // give ownership back to the container ``` -------------------------------- ### Boost.Assign for ptr_multimap Insertion Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/doc/tutorial Demonstrates using Boost.Assign's `ptr_map_insert` helper functions to simplify the insertion of elements into a `boost::ptr_multimap`, improving code readability. ```cpp boost::ptr_multimap animals; using namespace boost::assign; ptr_map_insert( animals )( "bobo", "bobo" ); ptr_map_insert( animals )( "bobo", "bobo" ); ptr_map_insert( animals )( "anna", "anna" ); ptr_map_insert( animals )( "anna", "anna" ); ``` -------------------------------- ### Boost C++ ptr_list push_front Method Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/doc/ptr_list Demonstrates the `push_front` methods for `boost::ptr_list`. The first overload takes a raw pointer, requiring it not to be null and granting ownership to the container. The second overload accepts compatible smart pointers, releasing ownership before insertion. ```cpp // Overload for raw pointer void push_front( T* x ); // Overload for compatible smart pointers template< class U > void push_front( _compatible-smart-ptr_ x ); ``` -------------------------------- ### Ownership Transfer to Boost Pointer Container Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/doc/conventions Details how Boost pointer containers take ownership of the pointers inserted into them. When a pointer is added, the container assumes responsibility for managing its lifetime (deallocation). This necessitates the container having its own copies or managing the lifetime directly, as demonstrated in the example where a new `animal` object is inserted. ```cpp #include struct animal {}; int main() { boost::ptr_vector vec; animal* ptr = new animal(); vec.push_back( ptr ); // Ownership of ptr is transferred to vec // ptr is now a dangling pointer if not managed carefully, // but vec will deallocate the animal object upon destruction. return 0; } ``` -------------------------------- ### Defining new_clone for Pointer Containers Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/doc/tutorial Illustrates how to define a free-standing `new_clone()` function in the same namespace as the `animal` class to enable pointer containers to create clones of `animal` objects. ```cpp inline animal* new_clone( const animal& a ) { return a.clone(); } ``` -------------------------------- ### Smart Pointer Interface Compatibility (C++) Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/doc/ptr_container Explains the transition from `std::auto_ptr` to `std::unique_ptr` in Boost.Pointer Container starting from Boost v. 1.67.0. For C++11/14 users, overloads for `std::unique_ptr` are provided. Code using `std::auto_ptr` is generally compatible, but explicit conversion might be needed. ```cpp // Use of _compatible-smart-ptr_ to indicate conditional interfaces. // For C++11/14 users, auto_ptr parameters now have std::unique_ptr overloads. // std::auto_ptr is still used for return types. // Implicit construction from std::auto_ptr to std::unique_ptr is possible until C++17. ``` -------------------------------- ### Prevent null pointer insertion in Boost pointer containers Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/doc/examples Demonstrates that null pointers (0 or nullptr) cannot be stored in Boost pointer containers. Attempting to push back, replace, or insert null pointers will throw a bad_ptr exception, whether passed directly or through std::auto_ptr. ```cpp my_container.push_back( 0 ); // throws bad_ptr my_container.replace( an_iterator, 0 ); // throws bad_ptr my_container.insert( an_iterator, 0 ); // throws bad_ptr std::auto_ptr p( 0 ); my_container.push_back( p ); // throws bad_ptr ``` -------------------------------- ### Implementing Animal Cloning Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/doc/tutorial Shows the implementation of a `clone()` method in the `animal` class, which is a prerequisite for pointer containers to effectively clone derived objects. ```cpp animal* animal::clone() const { return do_clone(); // implemented by private virtual function } ``` -------------------------------- ### Cloning ptr_list Contents with assign Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/doc/tutorial Demonstrates how to use the `assign()` method of `boost::ptr_list` to create a deep copy of another list by cloning its elements. ```cpp typedef boost::ptr_list zoo_type; zoo_type zoo, another_zoo; ... another_zoo.assign( zoo.begin(), zoo.end() ); ``` -------------------------------- ### Allowing Null Pointers with `nullable` in Boost Pointer Container Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/doc/conventions Demonstrates how to allow null pointers within a Boost pointer container by using `boost::nullable`. Without `nullable`, inserting a null pointer throws a `bad_pointer` exception. This example shows a successful insertion of a null pointer into a `ptr_vector` of nullable animals. ```cpp #include #include struct animal {}; int main() { boost::ptr_vector< boost::nullable > vec; vec.push_back( 0 ); // ok return 0; } ``` -------------------------------- ### Demonstrate Boost.Pointer Container ptr_vector Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/test/simple_test Illustrates the usage of boost::ptr_vector and a standard std::vector. It shows how to initialize both containers with new Poly objects, access elements using automatic indirection with ptr_vector, and replace elements, highlighting that ptr_vector automatically deletes the old element upon replacement. ```C++ void simple_test() { enum { size = 2000 }; typedef vector vector_t; typedef boost::ptr_vector ptr_vector_t; vector_t svec; ptr_vector_t pvec; for( int i = 0; i < size; ++i ) { svec.push_back( PolyPtr( new Poly ) ); pvec.push_back( new Poly ); // no extra syntax } for( int i = 0; i < size; ++i) { svec[i]->foo(); pvec[i].foo(); // automatic indirection svec[i] = PolyPtr( new Poly ); pvec.replace( i, new Poly ); // direct pointer assignment not possible, original element is deleted } for( vector_t::iterator i = svec.begin(); i != svec.end(); ++i ) (*i)->foo(); for( ptr_vector_t::iterator i = pvec.begin(); i != pvec.end(); ++i ) i->foo(); // automatic indirection } ``` -------------------------------- ### Define Tree and Node Structures with ptr_vector - C++ Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/test/tree_test Defines the core classes `tree` and `node` for representing a tree structure. The `tree` class utilizes `boost::ptr_vector` to manage its children, enabling polymorphic behavior. Node types include `inner_node` (which can also contain children) and `leaf` (holding specific data). ```cpp #include "test_data.hpp" #include #include #include #include #include #include #include using namespace std; using namespace boost; class node; class tree { typedef ptr_vector nodes_t; nodes_t nodes; protected: void swap( tree& r ) { nodes.swap( r.nodes ); } public: typedef nodes_t::iterator iterator; typedef nodes_t::const_iterator const_iterator; public: void add_child( node* n ); void remove( iterator n ); void write_tree( ostream& os ) const; size_t size() const; node& child( size_t idx ); const node& child( size_t idx ) const; iterator child_begin(); const_iterator child_begin() const; iterator child_end(); const_iterator child_end() const; iterator find( const string& match ); }; class node : noncopyable { virtual size_t do_node_size() const = 0; virtual string do_description() const = 0; virtual void do_write_value( ostream& os ) const = 0; public: virtual ~node() { } size_t node_size() const { return do_node_size(); } string description() const { return do_description(); } void write_value( ostream& os ) const { do_write_value( os ); } }; class inner_node : public node, public tree { string name; virtual size_t do_node_size() const { return tree::size(); } virtual string do_description() const { return lexical_cast( name ); } virtual void do_write_value( ostream& os ) const { os << " inner node: " << name; } void swap( inner_node& r ) { name.swap( r.name ); tree::swap( r ); } public: inner_node() : name("inner node") { } inner_node( const string& r ) : name(r) { } inner_node* release() { inner_node* ptr( new inner_node ); ptr->swap( *this ); return ptr; } }; template< class T > class leaf : public node { T data; virtual size_t do_node_size() const { return 1; } virtual string do_description() const { return lexical_cast( data ); } virtual void do_write_value( ostream& os ) const { os << " leaf: " << data; } public: leaf() : data( T() ) { } leaf( const T& r ) : data(r) { } void set_data( const T& r ) { data = r; } }; ``` -------------------------------- ### Using ptr_deque for Animal Management (C++) Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/test/tut1 This C++ code demonstrates the use of 'boost::ptr_deque' within a 'farm' class to manage a collection of 'animal' objects. It showcases how 'ptr_deque' handles object ownership, enables iteration, and supports transferring animals via 'auto_type'. ```cpp // // Then we, of course, need a place to put all // those animals. // class farm { // // This is where the smart containers are handy // typedef boost::ptr_deque barn_type; barn_type barn; #if !defined(BOOST_NO_CXX11_SMART_PTR) && !(defined(BOOST_MSVC) && BOOST_MSVC == 1600) && !BOOST_WORKAROUND(BOOST_GCC, < 40600) typedef std::unique_ptr raii_ptr; #else typedef std::auto_ptr raii_ptr; #endif // // An error type // struct farm_trouble : public std::exception { }; public: // // We would like to make it possible to // iterate over the animals in the farm // typedef barn_type::iterator animal_iterator; // // We also need to count the farm's size... // typedef barn_type::size_type size_type; // // And we also want to transfer an animal // safely around. The easiest way to think // about '::auto_type' is to imagine a simplified // 'std::auto_ptr' ... this means you can expect // // T* operator->() // T* release() // deleting destructor // // but not more. // typedef barn_type::auto_type animal_transport; // // Create an empty farm. // farm() { } // Default constructor // // We need a constructor that can make a new // farm by cloning a range of animals. // farm( animal_iterator begin, animal_iterator end ) : // // Objects are always cloned before insertion // unless we explicitly add a pointer or // use 'release()'. Therefore we actually // clone all animals in the range // barn( begin, end ) { } // Constructor for cloning a range // // ... so we need some other function too // animal_iterator begin() { return barn.begin(); } animal_iterator end() { return barn.end(); } // // Here it is quite ok to have an 'animal*' argument. // The smart container will handle all ownership // issues. // void buy_animal( animal* a ) // Takes ownership of the animal pointer { barn.push_back( a ); } // // The farm can also be in economical trouble and // therefore be in the need to sell animals. // animal_transport sell_animal( animal_iterator to_sell ) // Returns an auto_type for safe transfer { if( to_sell == end() ) ``` -------------------------------- ### Define Photon Data Structure and Sorting Criteria Source: https://www.boost.org/doc/libs/latest/libs/ptr_container/test/view_example Defines a 'photon' struct with random color, direction, and power attributes, along with three comparison structs ('sort_by_color', 'sort_by_direction', 'sort_by_power') for sorting photons based on these attributes. These are used as predicates for sorting. ```cpp // // This is our simple example data-structure. It can // be ordered in three ways. // struct photon { photon() : color( rand() ), direction( rand() ), power( rand() ) { }'s int color; int direction; int power; }; // // Our first sort criterium // struct sort_by_color { typedef photon first_argument_type; typedef photon second_argument_type; typedef bool result_type; bool operator()( const photon& l, const photon& r ) const { return l.color < r.color; } }; // // Our second sort criterium // struct sort_by_direction { typedef photon first_argument_type; typedef photon second_argument_type; typedef bool result_type; bool operator()( const photon& l, const photon& r ) const { return l.direction < r.direction; } }; // // Our third sort criterium // struct sort_by_power { typedef photon first_argument_type; typedef photon second_argument_type; typedef bool result_type; bool operator()( const photon& l, const photon& r ) const { return l.power < r.power; } }; ```