Boost logo

Boost :

Subject: [boost] Temporary objects
From: DE (satan66613_at_[hidden])
Date: 2009-10-29 15:42:42


hi all

unfortunately i'm totally out of time now
so i only write my proposal and an example
forgive me for that

the code

    #include <algorithm>
    template<typename type>
    class temporary : public type
    {
      temporary() : type() {}
      temporary(temporary &a) : type()
      {
        using std::swap;
        swap(static_cast<type&>(*this), static_cast<type&>(a));
      }
      template<typename other>
      temporary(const other &a) : type(a) {}
      temporary &operator=(temporary &a)
      {
        using std::swap;
        swap(static_cast<type&>(*this), static_cast<type&>(a));
        return *this;
      }
      template<typename other>
      temporary &operator=(const other &a)
      { type::operator=(a); return *this; }
    };

example1

    temporary<huge_type> foo(const huge_type &a)
    {//returning temporary object
      temporary<huge_type> ret; //or even 'ret(a)'
      //doing something...
      return ret;
    }
    //...
    huge_type result;
    result = foo(bar); //somewhere in code

only one copy operation -- assignment operator
return by value copying overhead is eliminated with help of swap()

example2

    struct my_type
    {
      //...
      my_type(temporary<my_type> &a) { this->swap(a); }
      //...
      my_type &operator=(temporary<my_type> &a)
      { this->swap(a); return *this; }
      //...
    };

    temporary<my_type> process(const my_type &item)
    {
      temporary<my_type> ret;
      //processing item...
      return ret;
    }
    //...
    my_type result = process(item); //somewhere in code
    //or
    result = process(item);

no temporary object handling overhead at all
return by value, copy-construct and assign from temporary objects for
free!

thank you for attention
    


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk