When using a container to store a copy of a custom type, pay attention to the overload assignment and copy constructor.

Source: Internet
Author: User

1. If a container saves a copy, the copy will be automatically deleted when the container is destroyed. If you use the container to store pointers, the objects pointed to by these pointers will not be deleted when the container is destroyed. Therefore, you must manually delete the objects before destroying the container.
2. If you use a container to store a copy, the process of saving and removing the copy is done by copying the constructor and the value assignment operator. If you do not explicitly provide the two, use the default copy constructor and value assignment operator. The implementation method is memory replication. For example, if you do not provide cfileattribute: Operator =, the statement fileattribute1 = fileattribute2 is equivalent to: memcpy (& fileattribute1, & fileattribute2, sizeof (cfileattribute )). If your cfileattribute contains only simple variables, for example:
Class cfileattribute
{
Int I;
Double D;
};
So there is nothing wrong with memcpy. HoweverIf your custom class contains (or nested contains) pointers, there may be problems because the replication of pointers is not equal to the replication of memory blocks.Therefore, you must provide a cfileattribute: Operator =, and copy the memory block corresponding to the pointer, this is the real copy (in this case, the pointers in the two replicas are not equal because they point to different memory blocks respectively ), the destruction of any of the replicas (usually destroying the memory block pointed to by the pointer in the Destructor at the same time) does not affect the independent existence of the other replicas.
Your cfileattribute: m_str is clearly of the cstring type, while cstring is of course a pointer internally. Therefore, the default copy constructor in memcpy mode and the value assignment operator will surely fail. You must explicitly provide your own copy constructors and value assignment operators.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.