So, I'm getting deeper into C++ than I did in school as part of a personal project I'm working on. I'm a Java developer, so memory management is a little hard to get used to again, and now that I'm going out of my way to code a certain way, I have a quick question about immutable classes.
When I think about them as a concept, I of course compare them to Strings in Java. But now that I'm in C++, a reassignment operation can potentially create a memory leak (or at least, I think it can). So now if I do this:
MyImmutableClass a ("blah");
a = a.modifyInSomeWay();
where modifyInSomeWay returns a new instance of MyImmutableClass开发者_Python百科, I haven't called the deconstructor. Is there something I'm missing here that would prevent the first assignment of 'a' from sticking around in memory?
In the case you've described, the assignment operator of MyImmutableClass
is called to copy the right hand side of the assignment to the left hand side (overwriting whatever was on the left hand side). If your class really is immutable, it won't even have an accessible assignment operator, and you will get a compile error.
If your object is mutable, and you do have a (correct) assignment operator, then there will be no memory leak because destructors for data on the left hand side will run as necessary to release memory. Writing a correct assignment operator can be tricky for some classes, though.
This concept of assigning directly to a (user-defined) object does not exist in Java, since over there everything is a reference.
The style of sharing immutable value objects which is found in lots of places in Java does not work very well in C++ due to its value semantics. Saying "the object should be immutable, but assignment should still work" is a contradiction. You could use variables of type shared_ptr<your_immutable_type>
, but that clutters up the code, and hence very few people do it in practice.
精彩评论