mardi 3 juillet 2018

Can the lifespan of a returning temporary variable be extentended by using move/swap c++11

I have a tree which base node is (not all methods are shown):

struct node_base {
    node_base(): _size(0),_parent(NULL) { }
    virtual ~node_base() {}

    virtual node_iterator_base& begin() const =0;
    virtual node_iterator_base& end()  const=0;

protected:
    size_t _size;
    node_base* _parent;
};

From that abstract class you can derive child classes which implement the needed container to hold all child nodes. As seen I also have a custom iterator node_iterator_base

struct node_iterator_base {
    virtual ~node_iterator_base() {}
    virtual node_iterator_base& operator++()=0;
    virtual node_base* operator->() const =0;
    virtual node_base& operator*() const =0;
    virtual bool operator==(const node_iterator_base& x) const =0;
    virtual bool operator!=(const node_iterator_base& x) const =0;
};
template<It>
struct derived_iterator: public node_iterator_base {
    derived_iterator(It I): ci(I) { }
    ...
    It ci;
}

The idea behind these base classes and their derived classes is to make it able to write something like this:

derived_node n;
for(node_iterator_base it=n.begin(); it!=n.end(); it++) {
    do_something(*it);
}

Now the problem is to implement begin in the derived class

node_iterator_base& derived_node::begin() const {
    return derived_iterator(container); 
    //This will not work because a temporary variable is passed to a 
    reference
}

What can be done instead? If we change the declaration of begin to

virtual node_iterator_base begin() const =0;

and

node_iterator_base derived_node::begin() {
    return derived_iterator(container); 
   //This will not work either because node_iterator_base is an abstract struct
}

Of course I could return a pointer but then my iterator will not look like a STL iterator and will have to destroy it manually. How can I return a reference? Can move/swap from C++11 help me? More about my heterogeneous tree here https://www.facebook.com/A-smart-tree-and-a-simple-parser-i-c-1678796648883396

Aucun commentaire:

Enregistrer un commentaire