I have the following setup:
A.h
class A
{
public:
...
const std::vector<int>& getSomeData() const;
private:
std::map<SomeIdType, std::shared_ptr<SomeDataType> > m_someDataCollection;
}
A.cpp
const std::vector<int>& getSomeData(SomeIdType id) const
{
std::vector<int> rVal;
auto it = m_someDataCollection.find(id);
if (it != m_someDataCollection.end())
{
std::shared_ptr<SomeDataType> someData = it->second;
rVal = someData->getSomeDataVector(); // returns std::vector<int>
}
return rVal;
}
int main()
{
SomeIdType id;
A a;
...
const std::vector<int>& data = a.getSomeData(id);
}
There is a reference to a local variable returned in A.cpp.
I don't want the vector returned by A::getSomeData() to be manipulated outside.
How can I achieve this goal, without having to return a reference to a local variable in A.cpp?
std::vector<int> getSomeData(SomeIdType id) const. whereas user can still modify returned vector, that doesn't affect the current class instance.someData->getSomeDataVector(); // returns std::vector<int>" that already does copy.return id-expression;naming a local variable is a move context, and a copy elision context)