1

in the for loop in main(), I use a myIterator itr variable, and I don't understand how it gets its values. Within the myIterator's copy constructor and another constructor I see he doesn't get visited (I put prints in them). So, how does itr get its values? (it uses the normal constructor once in the begin() return)

class list
{

public:
    Node *head;
    Node *last;

    list()
    {
        head = nullptr;
        last = nullptr;
    }

    list &add(Node &newNode)
    {
        if (!head)
        {
            head = &newNode;
            last = &newNode;
        }
        else
        {

            last->next = &newNode;
            last = &newNode;
        }
        return *this;
    }

    class myIterator
    {
    public:
        Node *np;
        myIterator(Node *p)
        {   cout<<"was in normal cons'"<<endl;
            np = p;
        }
        myIterator(const myIterator &other)
        {
            cout << "was in copy constr' " << endl;
            np = other.np;
        }
    };
    myIterator begin()
    {
        return myIterator(this->head);
    }
    myIterator end()
    {
        return myIterator(nullptr);
    }
};

int main()
{
    Node n1 = 99;   
    list l;
    l.add(n1);
    list::myIterator itr=l.begin(); //use in nornal cons'

    cout<<itr.np->data<<endl;

    
}

this print : was in normal cons' 99

  • 4
    The return value from `l.begin()` is constructed directly into `itr`. The compiler does **not** create a temporary and then a copy. See [What is copy elision and return value optimization](https://stackoverflow.com/questions/12953127/what-are-copy-elision-and-return-value-optimization) – BoP Jun 17 '22 at 07:27
  • 1
    Does this answer your question? [What are copy elision and return value optimization?](https://stackoverflow.com/questions/12953127/what-are-copy-elision-and-return-value-optimization) – Ulrich Eckhardt Jun 17 '22 at 07:59

0 Answers0