Reference in place of getters?

后端 未结 2 737
情书的邮戳
情书的邮戳 2021-01-27 04:00

in C++ is it a bad practice to use reference in place of getters?

for example:

class X
{
    int mP;
 public:
    const int& P;
    X():P(mP){}
}; 
<         


        
2条回答
  •  滥情空心
    2021-01-27 04:42

    Just think about refactoring to make the access thread safe, that won't work well this way and require a lot of changes in the client classes/functions.

    If you have class members, that are guaranteed not to be changed over lifetime of the instance, you can simply provide const int P; and initialize it properly in your class' constructors.

    If the value is to be visible class wide use a static const int P;

    In any other case use a public getter:

    int P() const; // a return type of 'const int &' would be redundant  
    

    1st shot implementation:

    int X::P() const
    {
        return mP;
    }
    

    Thread safe implementation:

    class X {
    {
        // ...
    private:
        // ...
        mutable std::mutex internalDataGuard;
    };
    
    int X::P() const
    {
        std::lock(internalDataGuard);
        return mP;
    }
    

提交回复
热议问题