Prev: redirect std::cout
Next: iterate trough vector of map
From: Robert Billing on 29 Apr 2010 09:31 I'm at the design stage of a package which will perform some operations on data objects of variable size, and converting myself to C++ after years of writing C. I can create a class to represent the objects I'm dealing with. The normal arithmetic operators are meaningful for these objects, so I plan to overload =, +, -, /, and *. The problem is this: Writing a = b + c * d ; where a, b, c and d are all instances of the class would work. When executed c * d would create a new instance, which would be anonymous, then another procedure would be called to add b and the first anonymous instance. This would create another new instance, and the operator = would copy it into a. The problem is this: Do the two anonymous temporaries get destroyed automatically, or if not what's the cleanest way of making sure they do get destroyed? I assume, from reading the source of a complex number package, that they do get destroyed, but I can't find any documentation that says they do for certain. Or have I simply got the wrong end of the stick?
From: John H. on 29 Apr 2010 11:43 Robert Billing wrote: > a = b + c * d ; > > The problem is this: Do the two anonymous temporaries get destroyed > automatically? Yes they will get destroyed automatically. Usually this will happen at the end of the statement, in this case after "a" has been assigned to. Once you get some code implemented, you can put a break point in the destructor and watch when and how many times it gets called. The exact rules around the creation and destruction of temporaries can be a little complicated. There is some freedom left to the implementation depending on the properties of the class, and optimizing compilers can do some surprising tricks. For details you can look in the C++ standard, in particular the [class.temporary] section. A footnote: this is a situation where you could use C++0x's "r-value references" concept to potentially make things more efficient (but doing so would probably be a case of premature optimization).
From: Robert Billing on 29 Apr 2010 12:41 We, the Senate of Arcturus, take note that John H. said: > Robert Billing wrote: >> a = b + c * d ; >> >> The problem is this: Do the two anonymous temporaries get destroyed >> automatically? > > Yes they will get destroyed automatically. Usually this will happen at > the end of the statement, in this case after "a" has been assigned to. Thanks, that's what I hoped. This makes the project very easy to implement. > A footnote: this is a situation where you could use C++0x's "r-value > references" concept to potentially make things more efficient (but doing > so would probably be a case of premature optimization). I looked that up. It seems very clever.
|
Pages: 1 Prev: redirect std::cout Next: iterate trough vector of map |