what is the difference

Hi everyone,

What is the diference between the two codes.(I think they are correct)?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// this is what my class looks like
template<typename TYPE>
class OrderdCollection
{
private:
  int container_size, container_capacity;
  TYPE* content;
public:
  OrderdCollection();
  OrderdCollection(const OrderedCollection& );
  ~OrderdCollection();
  // assignment operator and many more functions

};


Now this is wher I am confused about the difference in my two codes???

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
template <typename TYPE>
OrderedCollection<TYPE>& OrderedCollection<TYPE>:: operator = (const OrderedCollection<TYPE>& OC)
{
	if(this == &OC)
		return *this;
	if(OC.container_size <= container_capacity)
	{
		for (int i = 0; i < OC.container_size; ++i)
		{
			content[i] = OC.content[i];
		}

		container_size += container_size - OC.container_size;
		container_size = OC.container_size;

		container_capacity = OC.container
		
		return *this;
	}

	delete[] conteent;

	content = new TYPE[OC.container_capacity]
	for(int i = 0; i < OC.container_size; ++i)
	{
		content[i] = OC.content[i];
	}
	container_size = OC.container_size;
	container_capacity = OC.container_capacity;

	return *this;
}


with this....

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
template <typename TYPE>
OrderedCollection<TYPE>& OrderedCollection<TYPE>:: operator = (const OrderedCollection<TYPE>& OC)
{
	if(this == &OC)
		return *this;
	if(OC.container_size <= container_capacity)
	{
		for (int i = 0; i < OC.container_size; ++i)
		{
			content[i] = OC.content[i];
		}

		container_size += container_size - OC.container_size;
		container_size = OC.container_size;

		container_capacity = OC.container
		
		return *this;
	}

	delete[] content;
         TYPE* temp = new TYPE[OC.container_capacity]; // this line is different
  	for(int i = 0; i < OC.container_size; ++i)
	{
		temp[i] = OC.content[i];// and in here as well
	}
	container_size = OC.container_size;
	container_capacity = OC.container_capacity;
         temp = content; // this line is different

	return *this;
}


thanks for the help
?
The first one obviously manipulates the content of the class (I guess line 21 is a typo).

The second one is nonsense. A temporary variable is manipulated and then overwritten by 'content' which is already deleted. And since 'content' still points to invalid data it's a subject to crash later on

If line 29 would be content = temp; it'd be at least not crash prone.

Using such a temporary variable would make sense if you'd have a multi threading environment (but then it must have been written differently)
Topic archived. No new replies allowed.