Pass the output of a function directly to a function that takes control parameters?

This is my first post, and I hope that everything will be fine. I tried to solve this problem for a while, but in the meantime switched to an intermediate variable. Well here is what I mean:

//from a pre-built library double getValue(int idx) { //Returns some value from within a class } //from a function I created void setValue(double &input) { //set some value here } 

I am currently running my program as follows:

 double numberOne; numberOne = getValue(0); setValue(numberOne); 

It works and compiles. I would like, however, to do something like the following:

 setValue(getValue(0)); 

However, I can’t get it right (I tried a few referencing links, but I'm just shooting in the dark). I would like to know if this is possible? Also, if possible, are there any advantages in speed / memory to execute it this way and not have an intermediate storage value (aka numberOne). This is not really a double-value type problem, but when its class is much larger, I would like to reduce the memory usage \ deep copy as much as possible for speed \ memory reasons.

On the side of the note, there are some books or online resources that can help me speed up work with my C ++ programs with other performance improvements in speed / memory usage.

Thanks in advance for any help you can provide.

+4
source share
3 answers

Change this:

 void setValue(double &input) 

to

 void setValue(double input) 

In the end, input must be correctly entered, and therefore setValue() should consider this as such. Here, performance is not worse if you go by value. However, for large classes, you can change it to a link to avoid copying and achieve better performance:

 void setValue(const VeryBigClass & input) 
+4
source

The return value of the function is temporary. There is a rule that you cannot bind a temporary link to a non-constant link, because it turned out to cause a lot of errors.

You can bind a temporary reference to const, although, for example,

 SetValue(const double& value); 

This may be useful for larger or more complex types, but for primitive types such as double, you can simply pass it by value

 SetValue(double value); 
+2
source

You convert your set value:

 void setValue(const double &input) { //set some value here } 

This should fix the problem.

If your "double" is big enough (it is useless here), there are advantages to getting a link. This way you only copy the part of the object that interests you in setvalue() .

0
source

All Articles