Wednesday, March 14, 2018

Variable initialize ways

Leave a Comment

I can initialize a boost::format variable in two ways: First:

void foo() {   boost::format format{"Hellow %1% %2%"};   format % "Dear" % "user";   // do something with format } 

Second way:

void foo() {   boost::format v = boost::format {"Hellow %1% %2%"} % "Dear" % "user";   // do something with format } 

Are there exist any overheads or trubles with second initialize way? Is there exist similar practic like in second case for initializing of variables?

Thank you.

3 Answers

Answers 1

The conversion to std::string requested in the 3rd example has a possible cost in execution time and memory usage, and can mislead someone reading the code. It's just unnecessary.

Answers 2

In my understanding:

The overhead in that case is not where we think it is. Interesting question though.

Let's see what the first function does:

boost::format format{"Hellow %1% %2%"}; format % "Dear" % "user"; 

This creates an instance of format. The second line does not affect any result to any other new variable. It "simply" uses an operator overload that is dealt with internally, by the class boost::format. No new assignment is made.

Which is the main difference with the second way to do it. You assign, on top of the work already done, the result to a new variable. Which, for large numbers of execution, might cost (test it!).

As often, though, and depending on how much code those functions process, declaring your functions as inline could be the real benefit here.

c++ inline functions

Hope it helps.

Answers 3

format % "Dear" % "user"; is just an expression that is also of type boost::format. As such there is no real difference between the two approaches (except for the values of the variables).

Yes, similar things exist for other types. E.g. replace format with int:

int i = int(10); i * 7 + 5; 

Is equivalent to

int(10) * 7 + 5; 

It's just the same expression. You can assign it too, because the result of 10*7+5 is still int:

int i = int(10) * 7 + 5; 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment