开发者

should I use member variable or declare variable inside functions?

I have a class UI to handle console I/O for my C++ prog开发者_Go百科ram. It will have 4-5 member functions that will use a variable 'string input' to get the cin input, and some of these functions will be recursive. Now I was wondering if I should declare 'string input' at the beginning of each of these functions, or if it was better to have a private member variable and just to input.clear() at the beginning of each function. What's the best choice, from a style p-o-v and an efficiency p-o-v?


If the string input is not persistently associated with your object in the long term, and is just being used locally in the short term, make it a local variable.

1) It's semantically what you mean anyway.

2) If you're calling yourself recursively, you probably want separate variables per recursive call, which local variables give you automatically.

3) From an efficiency standpoint, a) the difference probably is too small to notice anyway, and b) it's probably faster to create a new variable on the stack than keep pointing at the object's member variable, unless construction of it is expensive.


Agree with dfan. Another point is if you define it as member variable, you probably need decouple your member functions implementation with knowledge of the source of this string. So that when you change the source of the string in future, e.g., you read it from a file I/O instead of std::cin, your methods will remain unchanged.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜