简体   繁体   中英

Const reference vs inline getter - C++

I have a class with a private field. This field is written only inside the class, but must be readable from outside. Which option is preferable and why? First, with const reference

class Test {
public:
    const int &field; // can read outside
    
    inline Test() noexcept: field(_field) {}
    
    void someMethod() {
        _field = 123; // writing occurs only inside the class
    }
private:
    int _field;
};

Or second, with inline getter:

class Test {
public:
    void someMethod() {
        _field = 123; // writing occurs only inside the class
    }
    
    inline int field() const noexcept { // can call outside
        return _field;
    }  
private:
    int _field;
};

There are a whole bunch of reasons to avoid the reference-typed data member:

  • It bloats the object size
  • All assignment operators default to deleted
  • The default copy-constructor becomes wrong, tying the lifetime of the new copy to that of the copied-from object.
  • The object is no longer standard-layout nor trivially copyable

If you really really want to expose a reference, do so as the return type of a member function:

const int& field() const { return field_; } // avoid leading underscores in application code

Generally though, a value return will be higher-performance and easier for the calling code to use.

  • Copying a small value is as cheap as forming a reference (which copies a pointer)
  • The compiler doesn't have to worry about aliasing
  • The programmer doesn't have to worry about aliasing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM