开发者

Value get changed even though I'm not using reference

In code:

struct Rep
    {
        const char* my_data_;
        Rep* my_left_;
        Rep* my_right_;
        Re开发者_StackOverflow社区p(const char*);
    };

typedef Rep& list;

ostream& operator<<(ostream& out, const list& a_list)
    {
        int count = 0;
        list tmp = a_list;//----->HERE I'M CREATING A LOCAL COPY
        for (;tmp.my_right_;tmp = *tmp.my_right_)
        {
            out << "Object no: " << ++count << " has name: " << tmp.my_data_;
            //tmp = *tmp.my_right_;
        }
        return out;//------>HERE a_list is changed
    }

I've thought that if I'll create local copy to a_list object I'll be operating on completely separate object. Why isn't so?

Thanks.


You've typedef'd list to be a Rep &. That means tmp isn't a copy. It's just another reference. Anything you do to tmp will be done to a_list.


const list& a_list - compiler error, reference to reference is illegal.

tmp = *tmp.my_right_ is very bad. Use pointers instead of reference. The thing is that tmp is reference to a_list. a_list is changed when you write tmp = *tmp.my_right_.


I assume list is meant to be the same as Rep.

You are only copying the the pointer to the first node in the list. You are not copying the data, nor the rest of the nodes of the list. You are doing a shallow copy of the first node of the list. If you would also copy the objects themselves it would be deep copy.


I'm assuming you're rolling your own list as an educational exercise. When you do this for real, know that the standard library provides all this functionality for you.

std::list<std::string> myData;

// One way to print everything in the list.
int count = 0;
for (std::list<std::string>::iterator i = myData.begin(); i != myData.end(); ++i)
{
    std::cout << "Object no: " << ++count << " has name: " << *i;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜