Musings

A random collection

Archive for the ‘Boost’ Category

C++: Smart Pointers

Many choices for Smart Pointers or Auto Pointers:

  1. Boost Smart Pointers
    1. Safe Pointers: Simple sole ownership of single objects
    2. Shared Pointers: Object ownership shared among multiple pointers
    3. Weak Pointers: Non-owning observers of an object owned by shared_ptr
    4. Intrusive Pointers: Shared ownership of objects with an embedded reference count
  2. STL Auto Pointers

What are some of the problems with std::auto_ptr?

auto_ptr is a ownership based smart-pointer. The auto_ptr owns the object it points to and is responsible for freeing the memory when it goes out of scope.

If a auto_ptr is assigned to another auto_ptr, the new auto_ptr becomes the owner and the old auto_ptr is set to NULL.

  1. auto_ptr has explicit constructor
    auto_ptr<int> p1(new int(21));  // ok
    auto_ptr<int> p2 = new int(101); // error!
    
  2. Problem with storing pointers to arrays
    auto_ptr<B> p1(new int[51]);  // problem with delete, does not call delete[]
    
  3. No pointer arithmetic supported
    ++p1; // error!
    *p1 = 10; // ok
    
  4. auto_ptr not suitable for STL containers
    vector< auto_ptr<int> > v; // invitation to problems
    sort(v.begin(), v.end()); // problems!!
    
  5. Copies of auto_ptr cause problems
    auto_ptr<int> p1(new int(101));
    auto_ptr<int> p2;
    
    p2 = p1; // p2 is owner of memory
    *p1 = 5; // error, p1 not owner anymore
    
    void f(auto_ptr<int> p) {}
    f(p2); // ownership transferred to temporary variable for passing by value
    
  6. Need to disallow unintentional ownership transfer, make it const. const auto_ptr will stop you from snatching ownership from it (will not allow – assignment, copy-ctor, release, reset)
    const auto_ptr<int> p1(new int(101));
    auto_ptr<int> p2;
    
    p2 = p1; // compilation error
    
    void f(auto_ptr<int> p) {}
    f(p1); // compiler error
    
  7. Class member auto_ptr objects should be declared const
    class A
    {
        const auto_ptr<B> p1;
    public:
        A(const A& that) : p1(new B(*that.p1)) {}
    
        A& operator=(const A& that)
        {
            if (this != &that)
            {
                // does not reset the pointer
                *p1 = *that.p1;
            }
        }
    
        // no destructor
        // ~A()
    };
    

More on “Using Auto Ptr Effectively

How do you implement a smart pointer?

template<typename X>
class SmartPtr
{
public:
    SmartPtr();
    explicit SmartPtr(X* p);      // always make single argument ctor explicit
    // SmartPtr(SmartPtr& that);  -- do not want this
    X* operator->();
    X* operator->() const;
    X& operator*();
    const X& operator*() const;
    operator void*() const;
    ~SmartPtr();
private:
    X* xptr;
};
Analysis
  1. Guess what design pattern is this? Proxy pattern
  2. Benefits summary: Less bugs (automatic cleanup, automatic initialization, dangling pointers), Exception Safety, Garbage Collection, Efficienct use of available memory(for Copy On Write – COW), in STL Containers (but don’t use std::auto_ptr for this).
  3. SmartPtr() initializes the NULL pointer. Ordinary pointer if left uninitialized may cause havoc if you happen to dereference it. SmartPtr makes sure it is at least initialized to NULL.

    When you dereference a pointer, if it is set to NULL, operator->() and operator*() can assert a failure. Which will not corrupt memory and instead will give predictable behavior of terminating your program.

    SmartPtr<SomeType> ptr1;  // initialized to 0, not to some random value
    *ptr1.field;                 // ASSERT failed!!!
    ptr1->field;                 // ASSERT failed!!!
    
  4. SmartPtr(X*) initializes the Smart pointer to the raw pointer and from now on will take the ownership of it. You get a safer pointer and you do not need to worry about releasing this memory anymore.
    {
        SmartPtr<SomeType> ptr1(new SomeType());
        // use ptr1 like a regular pointer
        ...
        // automatically release memory when going out of scope
    }
    
  5. Make SmartPtr(X*) explicit to ensure that no inadvertent conversions cause problems. Without explicit, the following code will be possible and may cause problems
    {
        SomeType* p1 = &obj1;
        SmartPtr<SomeType> ptr1(new SomeType());
    
        if (ptr1 == p1) 
            // Without explicit p1 will be converted to SmartPtr(p1)
            // and will be automatically lead to delete p1
        {
        }
    }
    
  6. What should we do on assignment, i.e. “operator=”? Create a new copy, Ownership transfer, Reference Counting, Reference Linking (keep a circular list of smart ptrs pointing to the same location), Copy on Write (reference count till no modification to the pointed object).
Advertisements

Written by curious

July 1, 2010 at 7:57 am

Posted in Boost, STL

C++: Boost Components

1 Accumulators Framework for incremental calculation, and collection of statistical accumulators. Math and Numerics
2 Any Safe, generic container for single values of different value types. Data Structures
3 Array STL compliant container wrapper for arrays of constant size. Containers
4 Asio Portable networking, including sockets, timers, hostname resolution and socket iostreams. Concurrent Programming, I/O
5 Assign Filling containers with constant or generated data has never been easier. I/O
6 Bimap Bidirectional maps library for C++. With Boost.Bimap you can create associative containers in which both types can be used as key. Containers, Data structures
7 Bind boost::bind is a generalization of the standard functions std::bind1st and std::bind2nd. It supports arbitrary function objects, functions, function pointers, and member function pointers, and is able to bind any argument to a specific value or route input arguments into arbitrary positions. Function Objects, Higher-order Programming
8 Call Traits Defines types for passing parameters. Generic Programming
9 Circular Buffer A STL compliant container also known as ring or cyclic buffer. Containers
10 Compatibility Help for non-conforming standard libraries. Broken Compiler workarounds
11 Compressed Pair Empty member optimization. Data structures, Miscellaneous
12 Concept Check Tools for generic programming. Generic Programming, Correctness and testing
13 Config Helps Boost library developers adapt to compiler idiosyncrasies; not intended for library users. Broken Compiler workarounds
14 Conversion Polymorphic and lexical casts. String and text processing, Miscellaneous
15 CRC The Boost CRC Library provides two implementations of CRC (cyclic redundancy code) computation objects and two implementations of CRC computation functions. The implementations are template-based. Miscellaneous
16 Date Time A set of date-time libraries based on generic programming concepts. Miscellaneous
17 Disjoint Sets Boost.DisjointSets provides disjoint sets operations with union by rank and path compression. Containers
18 Dynamic Bitset The dynamic_bitset class represents a set of bits. It provides accesses to the value of individual bits via an operator[] and provides all of the bitwise operators that one can apply to builtin integers, such as operator& and operator<<. The number of bits in the set is specified at runtime via a parameter to the constructor of the dynamic_bitset. Containers
19 Enable If Selective inclusion of function template overloads. Generic Programming
20 Exception The Boost Exception library supports transporting of arbitrary data in exception objects, and transporting of exceptions between threads. Miscellaneous
21 Filesystem The Boost Filesystem Library provides portable facilities to query and manipulate paths, files, and directories. Miscellaneous
22 Flyweight Design pattern to manage large quantities of highly redundant objects. Miscellaneous
23 Foreach In C++, writing a loop that iterates over a sequence is tedious. We can either use iterators, which requires a considerable amount of boiler-plate, or we can use the std::for_each() algorithm and move our loop body into a predicate, which requires no less boiler-plate and forces us to move our logic far from where it will be used. In contrast, some other languages, like Perl, provide a dedicated “foreach” construct that automates this process. BOOST_FOREACH is just such a construct for C++. It iterates over sequences for us, freeing us from having to deal directly with iterators or write predicates. Algorithms
24 Format The format library provides a class for formatting arguments according to a format-string, as does printf, but with two major differences: format sends the arguments to an internal stream, and so is entirely type-safe and naturally supports all user-defined types; the ellipsis (…) can not be used correctly in the strongly typed context of format, and thus the function call with arbitrary arguments is replaced by successive calls to an argument feeding operator%. String and text processing, I/O
25 Function Function object wrappers for deferred calls or callbacks. Function objects and higher-order programming, Programming Interfaces
26 Function Types Boost.FunctionTypes provides functionality to classify, decompose and synthesize function, function pointer, function reference and pointer to member types.
27 Functional The Boost.Function library contains a family of class templates that are function object wrappers.
28 Functional/Factory Function objects for dynamic and by-value construction.
29 Functional/Forward Function object adapters to address the forwarding problem.
30 Functional/Hash A TR1 hash function object that can be extended to hash user defined types.
31 Fusion Library for working with tuples, including various containers, algorithms, etc.
32 GIL Generic Image Library
33 Graph The BGL graph interface and graph components are generic, in the same sense as the the Standard Template Library (STL).
34 In Place Factory, Typed In Place Factory Generic in-place construction of contained objects with a variadic argument-list.
35 Integer The organization of boost integer headers and classes is designed to take advantage of types from the 1999 C standard without resorting to undefined behavior in terms of the 1998 C++ standard. The header makes the standard integer types safely available in namespace boost without placing any names in namespace std.
36 Interprocess Shared memory, memory mapped files, process-shared mutexes, condition variables, containers and allocators.
37 Interval Extends the usual arithmetic functions to mathematical intervals.
38 Intrusive Intrusive containers and algorithms.
39 IO State Savers The I/O sub-library of Boost helps segregate the large number of Boost headers. This sub-library should contain various items to use with/for the standard I/O library.
40 Iostreams Boost.IOStreams provides a framework for defining streams, stream buffers and i/o filters.
41 Iterators The Boost Iterator Library contains two parts. The first is a system of concepts which extend the C++ standard iterator requirements. The second is a framework of components for building iterators based on these extended concepts and includes several useful iterator adaptors.
42 Lambda Define small unnamed function objects at the actual call site, and more.
43 Lexical Cast General literal text conversions, such as an int represented a string, or vice-versa, from Kevlin Henney.
44 Math Boost.Math includes several contributions in the domain of mathematics: The Greatest Common Divisor and Least Common Multiple library provides run-time and compile-time evaluation of the greatest common divisor (GCD) or least common multiple (LCM) of two integers. The Special Functions library currently provides eight templated special functions, in namespace boost. The Complex Number Inverse Trigonometric Functions are the inverses of trigonometric functions currently present in the C++ standard. Quaternions are a relative of complex numbers often used to parameterise rotations in three dimentional space. Octonions, like quaternions, are a relative of complex numbers.
45 Math Common Factor Greatest common divisor and least common multiple.
46 Math Octonion Octonions.
47 Math Quaternion Quaternions.
48 Math/Special Functions A wide selection of mathematical special functions.
49 Math/Statistical Distributions A wide selection of univariate statistical distributions and functions that operate on them.
50 Member Function Generalized binders for function/object/pointers and member functions.
51 Min-Max Standard library extensions for simultaneous min/max and min/max element computations.
52 MPI Message Passing Interface library, for use in distributed-memory parallel application programming.
53 MPL The Boost.MPL library is a general-purpose, high-level C++ template metaprogramming framework of compile-time algorithms, sequences and metafunctions. It provides a conceptual foundation and an extensive set of powerful and coherent tools that make doing explict metaprogramming in C++ as easy and enjoyable as possible within the current language.
54 Multi-Array Boost.MultiArray provides a generic N-dimensional array concept definition and common implementations of that interface.
55 Multi-Index The Boost Multi-index Containers Library provides a class template named multi_index_container which enables the construction of containers maintaining one or more indices with different sorting and access semantics.
56 Numeric Conversion Optimized Policy-based Numeric Conversions.
57 Operators Templates ease arithmetic classes and iterators.
58 Optional Discriminated-union wrapper for optional values. Miscellaneous
59 Parameter Boost.Parameter Library – Write functions that accept arguments by name.
60 Pointer Container Containers for storing heap-allocated polymorphic objects to ease OO-programming.
61 Pool Memory pool management.
62 Preprocessor Preprocessor metaprogramming tools including repetition and recursion.
63 Program Options The program_options library allows program developers to obtain program options, that is (name, value) pairs from the user, via conventional methods such as command line and config file.
64 Property Map Concepts defining interfaces which map key objects to value objects.
65 Property Tree A tree data structure especially suited to storing configuration data.
66 Proto Expression template library and compiler construction toolkit for domain-specific embedded languages.
67 Python The Boost Python Library is a framework for interfacing Python and C++. It allows you to quickly and seamlessly expose C++ classes functions and objects to Python, and vice-versa, using no special tools — just your C++ compiler.
68 Random A complete system for random number generation.
69 Range A new infrastructure for generic algorithms that builds on top of the new iterator concepts.
70 Rational A rational number class.
71 Ref A utility library for passing references to generic functions.
72 Regex Regular expression library.
73 Result Of Determines the type of a function call expression.
74 Scope Exit Execute arbitrary code at scope exit. Miscellaneous
75 Serialization Serialization for persistence and marshalling.
76 Signals Managed signals & slots callback implementation.
77 Signals2 Managed signals & slots callback implementation (thread-safe version 2).
78 Smart Ptr Smart pointer class templates.
79 Spirit LL parser framework represents parsers directly as EBNF grammars in inlined C++.
80 Statechart Boost.Statechart – Arbitrarily complex finite state machines can be implemented in easily readable and maintainable C++ code. Miscellaneous
81 Static Assert Static assertions (compile time assertions).
82 String Algo String algorithms library.
83 Swap Enhanced generic swap function. Miscellaneous
84 System Operating system support, including the diagnostics support that will be part of the C++0x standard library. Miscellaneous
85 Test Support for simple program testing, full unit testing, and for program execution monitoring.
86 Thread Portable C++ multi-threading.
87 Timer Event timer, progress timer, and progress display classes. Miscellaneous
88 Tokenizer Break of a string or other character sequence into a series of tokens.
89 TR1 The TR1 library provides an implementation of the C++ Technical Report on Standard Library Extensions. This library does not itself implement the TR1 components, rather it’s a thin wrapper that will include your standard library’s TR1 implementation (if it has one), otherwise it will include the Boost Library equivalents, and import them into namespace std::tr1. Miscellaneous
90 Tribool 3-state boolean type library. Miscellaneous
91 Tuple Ease definition of functions returning multiple values, and more.
92 Type Traits Templates for fundamental properties of types.
93 Typeof Typeof operator emulation. Miscellaneous
94 uBLAS uBLAS provides matrix and vector classes as well as basic linear algebra routines. Several dense, packed and sparse storage schemes are supported.
95 Units Zero-overhead dimensional analysis and unit/quantity manipulation and conversion. Miscellaneous
96 Unordered Unordered associative containers. Containers
97 Utility Class noncopyable plus checked_delete(), checked_array_delete(), next(), prior() function templates, plus base-from-member idiom. Algorithms, Function objects and higher-order programming, Memory, Miscellaneous
98 Uuid A universally unique identifier. Data Structures
99 Value Initialized Wrapper for uniform-syntax value initialization, based on the original idea of David Abrahams. Miscellaneous
100 Variant Safe, generic, stack-based discriminated union container. Containers, Data structures
101 Wave The Boost.Wave library is a Standards conformant, and highly configurable implementation of the mandated C99/C++ preprocessor functionality packed behind an easy to use iterator interface. String and text processing
102 Xpressive Regular expressions that can be written as strings or as expression templates, and which can refer to each other and themselves recursively with the power of context-free grammars. String and text processing

Written by curious

June 23, 2010 at 9:43 am

Posted in Boost

Tagged with

TECH: Building Boost On Linux & Windows

Ensure that you have the following packages:

  1. zlib-devel bzip2-devel
  2. openmpi-devel
  3. python-devel
  4. libicu libicu-devel

Run the following:

./bootstrap.sh --prefix=/opt/boost --without-icu
./bjam install

On Windows

bootstrap.bat
.\bjam --prefix=c:\boost_1_43_0 --without-python --without-mpi install

.\bjam toolset=msvc --build-type=complete --libdir=C:\Boost\lib\i386 install

# specify Visual Studio version number to use a specific tool chain
.\bjam toolset=msvc-9.0 --build-type=complete --libdir=C:\Boost\lib\i386 install

Build 64-bit on Windows (32-bit)

bjam msvc architecture=x86 address-model=64 --prefix=c:\boost_1_44_0 --without-python --without-mpi stage
bjam msvc architecture=x86 address-model=64 --prefix=c:\boost_1_44_0 --without-python --without-mpi install

bjam.exe toolset=msvc --build-type=complete architecture=x86 address-model=64 --libdir=C:\Boost\lib\x64 install -j%NUMBER_OF_PROCESSORS%

To override Visual Studio Version, edit project-config.jam file

using msvc : 9.0 ;

Written by curious

April 20, 2010 at 1:22 pm

Posted in Boost

Tagged with