I am a little confused right now regarding C++ reference semantics. Suppose I have a class that returns a const reference:
class foo
{
private:
std::map<int, int> stuff;
public:
const std::map<int, int>& getStuff()
{
return stuff;
}
};
And I use it as follows:
foo f;
const std::map<int, int>& s = f.getStuff();
which is fine, but if I were to use it as follows:
foo f;
std::map<int, int> s = f.getStuff();
What happens exactly?
If I understand correctly, a const reference to stuff was returned and a copy created into s on which I can wreak havoc. Would there be any way to avoid this?
edit:
So there is no way to avoid the copy constructor being called here, for std::map anyways…
Short answer: no, you can’t prevent it. The client can’t modify the original, but if you give the client read-access to the map, then the client is responsible for not doing stupid things with the information; the class can’t possibly prevent that.
Longer answer: maybe, but not really. If you really want to make copying difficult, you can wrap the map in a class with private copy constructor and assignment operator. That way the
sassignment will be illegal (rejected by the compiler). The client will still be able to read the elements of the map piecemeal and populate a new map with them — a manual copy — but the only way to prevent that is to restrict the read-access in the wrapper class, which kind of defeats the purpose ofgetStuff.