| re: simple memory question
G'day,
Shailesh Humbad wrote:
[color=blue]
> In the code below, I don't understand how push_front can make a deep
> copy of the locally declared dataElement object. I thought the
> default copy constructor only copies the members of the class, or is
> it just that the local dataElement object persists in the linked list
> even after addTo returns. Can someone explain why, or point to an
> appropriate section of the C++ faq/reference?
>
> -----------COMPLETE CODE-----------
> #include <iostream>
> #include <list>
> using namespace std;
>
> class dataElement {
> public:
> char * szM;[/color]
If you really want to use char* - std::string would be better.
[color=blue]
> };
>
> void addTo(list<class dataElement> &L) {
> class dataElement myD;[/color]
The 'class' keyword is redundant here. Simply "list<dataElement>" and
"dataElement myD"
[color=blue]
> myD.szM = (char*)malloc(sizeof(char)*3);[/color]
Better to use new, ie "myD.szM = new char[3]"
[color=blue]
> myD.szM[0] = 'a';
> myD.szM[1] = 'b';
> myD.szM[2] = '\0';
> L.push_front(myD);
> }
>
> int main(int argc, char* argv[])
> {
> class dataElement deTemp;
> list<class dataElement> L;
>
> addTo(L);
>
> deTemp = L.front();
>
> cout << "output: " << deTemp.szM << "\n";
> // Prints "output: 100 ab"
>
> return 0;
> }[/color]
The push_front method is indeed making a shallow copy of your dataElement.
The fact that the data persists after the addTo call is due to the memory
allocated there not being freed up so the copy of the pointer in the list
is still referring to a valid location.
--
Cheers,
Gryff |