Getters and Setters. Is there performance overhead?

后端 未结 4 1800
余生分开走
余生分开走 2021-02-01 13:54

I have a Particle System Engine in my C++ project and the particles themselves are just structs of variables with no functions. Currently, each particle (Particle) is updated fr

4条回答
  •  南方客
    南方客 (楼主)
    2021-02-01 14:43

    There could be various answers to this question, but I put my thoughts here.

    For the performance, the cost can be mostly ignored for simple POD type. But there 's still cost, and it depends on what type you return. For particle, there couldn't be much data. If this is a image class (like OpenCV cv::Mat), or 3d data (like PolyData in VTK), it is better that setter/getter deals with pointers/iterators than the actual data to avoid memory allocation problem.

    When you want to template things, the setter/getter can be a lot useful to avoid inexplicit type conversion. A setter/getter can be a way to access private/protected member, which is also allows you to avoid using x as the common name of variable. More over, the setter/getter can return a Lvalue reference which allows you to do particle.getX() = 10.0 ;

提交回复
热议问题