Home >Backend Development >C++ >Why Does Adding a New Value to a List Overwrite Previous Values When Using Reference Types?
Understanding List
The provided code demonstrates a common pitfall when using reference types with lists. The Tag
class, being a reference type, means variables hold a reference to the object's memory location, not a copy of the object itself.
Within the loop, the same _tag
instance is repeatedly modified. Each addition to the list doesn't create a new Tag
object; instead, it adds another reference to the same _tag
object. Therefore, the final list contains multiple references pointing to the last modified state of _tag
.
Why Using struct
Solves the Problem
Changing public class Tag
to public struct Tag
resolves the issue because structs are value types. When a struct is assigned, a copy of the struct's data is created. Consequently, each iteration of the loop creates a completely independent _tag
instance. Modifications to one instance don't affect others, resulting in a list with unique Tag
objects.
Derived Collection Class Relevance
The problem isn't inherent to the TagCollection
class's design. The TagCollection
class itself appears correctly implemented. The core issue lies in how the _tag
instance is handled within the loop that populates the list, specifically the repeated modification of a single reference type instance.
The above is the detailed content of Why Does Adding a New Value to a List Overwrite Previous Values When Using Reference Types?. For more information, please follow other related articles on the PHP Chinese website!