简体   繁体   中英

C++ interface returns a reference - is it a bad practice?

I'm trying to implement several caching algorithms, where one can replace another in runtime.

So I've started with describing an interface:

class ICache
{
  public:
    virtual ~ICache(){}
    virtual const std::vector<SomeValue>& getSomeValues() const = 0;
    virtual const std::vector<AnotherValue>& getAnotherValues() const = 0;
    ...
}

And here comes my question - is it a bad practice to return a reference in interface?

Such design enforce and exposure an internal implementation of class, which implements it (as it "has to" store all vectors as members).

Is there a better way?

I don't see any difficulty with returning references in this context. The interface is just a contract between the caller and the service. I agree that the nature of this contract seems to imply that it is better on the cache side to store the data internally this way but doesn't force the implementation to do so; and from an implementation point of view it allows a mechanism which can be very efficient when used correctly (as opposed to forcing the creation of a new vector and passing it by value).

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