简体   繁体   中英

const correctness with boost shared_ptr

I've implemented a cache class, which is able to fill/extract records in a threadsafe way (is not shown in the example). But i have some doubts about the const correctness of this class.

Given is the following class:

public:

void add(const Record& record)
{
    boost::shared_ptr<Record> rec(new Record(record));
    _records.push(rec);
}

std::vector<boost::shared_ptr<Record> getRecords() const
{
    return _records;
}

private:

std::vector<boost::shared_ptr<Record> > _records;

Here the getRecords() function returns the content of the cache. But every other class which gets the records is able to modify the records, isn't it?!

So I want to return the cache as a container of const records.

My new implementation looks like this:

public:

void add(const Record& record)
{
    boost::shared_ptr<const Record> rec(new Record(record));
    _records.push(rec);
}

std::vector<boost::shared_ptr<const Record> getRecords() const
{
    return _records;
}

private:

std::vector<boost::shared_ptr<const Record> > _records;

Is this the correct way to implement the needed functionality?

In principle, you are right, declaring the member as std::vector<boost::shared_ptr<const Record> > _records; does prevent client code from modifying the pointee object stored in your class. There is another detail worth pointing out:

std::vector<boost::shared_ptr<const Record> getRecords() const

This method returns the vector by value. Client code will hence always operate on a copy of the vector of Record elements, which requires every element in the container to be copied - if that's not a requirement, you might consider changing your method signature such that it returns a reference:

std::vector<boost::shared_ptr<const Record>& getRecords() const

which is more efficient when client code operates on the reference.

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