Two different words for getters by reference vs getters by copy

Consider the following example :

class MyClass
{
    // Getters by copy ?
    public:
        inline std::string fullName() const {return _firstName+_lastName;}

    // Getters by reference ?
    public:
        inline const std::string& firstName() const {return _firstName;}
        inline const std::string& lastName() const {return _lastName;}

    // Data members
    protected:
        std::string _firstName;
        std:::string _lastName;
}

In the documentation of my code, I would like to distinguish between getters by reference (direct access of the class data members) and getters by copy (access to data constructed on class data members). What words can I use to name these two different categories ?


The first question that comes to mind is why you want to distinguish the operations in the name. Specially since that separation implies that you are leaking details of your implementation to the users and losing encapsulation.

Consider for example that during profiling of the real application you find out that 90% of the time callers use fullName() and don't make copies, then you might want to modify your type to cache the result and avoid the cost:

class MyClass {
   // ...
   std::string _fullName;
public:
   const std::string& fullName() const {
      return _fullName;
   }
   // One of the options for caching: update on set
   // Could use other, like update on first request...
   void setName( std::string firstName ) {
      _firstName = std::move(firstName);
      _fullName = _firstName + _lastName;
   }
};

If your naming convention differentiates both types of functions, then you would either have to seek all uses of the function in your project and replace them for a change in the implementation, or else your function would be lying as the naming implies a copy, but the implementation does not.

That being said, I have seen this done in the past, where accessor that just return a reference to the member were named either by the nember or getMember , and operations that create new objects were named as a sentence with a verb that implied the construction: composeFullName to imply that there is a cost associated with calling the operation. This change in the naming conventions, where I have seen it, was specific to operations where the cost of executing it was high.

链接地址: http://www.djcxy.com/p/94572.html

上一篇: libclang:在AST中缺少一些语句?

下一篇: 通过引用与getter通过复制获得两个不同的单词