Calling this->get/this->set methods versus directly accesing member variables in C++

前端 未结 8 635
挽巷
挽巷 2021-01-18 18:21

Suppose I have a class Foo, with a private variable bar_ containing some state for Foo. If necessary, I may write public get/set metho

相关标签:
8条回答
  • 2021-01-18 19:24

    If your compiler does any inlining at all, it will be able to inline get and set methods defined and used within a given class. const has no bearing on this, and the inline directive doesn't make much difference either.

    I generally prefer to use my get() and set() methods even from within the class definition, when I can. You get all the same benefits that you get by using them outside the class definition, and there is no speed penalty.

    0 讨论(0)
  • 2021-01-18 19:26

    I have no justification other than concerns regarding the speed of directly accessing the variable versus calling the methods, but I suspect that if the get/set methods are defined inline (which they are) it shouldn't make a difference. Does it make a difference? Does constness play a role in this?

    The inline keyword hardly plays a role in whether or not the compiler does any inlining. The use for the keyword in that regard is essentially deprecated. Modern compilers inline like crazy, and they know when to do it better tan any programmer does.

    Any compiler worth dirt will say "Hm, call this function to get this member variable; hey I can just get the member variable!" You're worrying about nothing. This happens regardless of any inline keywords.

    That said, I almost always use the member functions. If I change how a variable behaves when it's accessed, I now "automatically" apply that everywhere it's used. Clean code should be your goal, though, not a dogmatic "always skip functions" or not.

    Anytime I just want a variable value, I use the corresponding member variable. (i.e, if I were writing std::vector, if I needed to check if the size was less than something, I'd say size() < x). But if it's cleaner to use the variable directly, do that instead, such as mSize++.

    const-ness is irrelevant. If you're in a non-const function, you'll use the non-const version of your getter, same with const. Obviously, using the members directly maintains const-ness. There is no difference.

    0 讨论(0)
提交回复
热议问题