I have some questions about returing a reference of a class member variable.
I have the following code:
#include <stdint.h>
#include <string>
#include <iostream>
#include <set>
void
PrintSet (const std::string & str, const std::set<uint32_t> & to_print)
{
std::cout << str << " (" << to_print.size () << "): ";
for (std::set<uint32_t>::const_iterator it = to_print.begin ();
it != to_print.end (); ++it)
{
std::cout << *it << " ";
}
std::cout << "\n";
}
class Test
{
private:
std::set<uint32_t> m_values;
public:
Test () : m_values () { }
void
SetValues (const std::set<uint32_t> & values)
{
m_values = values;
}
const std::set<uint32_t> &
GetValues () const
{
return m_values;
}
std::set<uint32_t> &
GetValues ()
{
return m_values;
}
void
Print () const
{
PrintSet ("TestInst", m_values);
}
};
I noticed that if I do this:
std::set<uint32_t> returned = test.GetValues ();
The variable
returned
gets a copy, not a reference, why?Does the
const std::set<uint32_t> & GetValues () const
function must contain the doubleconst
(the one on the return value and the one after the function name) ?
EDIT: Additional questions:
Knowing that
std::set<uint32_t> returned = test.GetValues ();
creates a copy. If I do this:test.GetValues ().size ();
In order to call the
size ()
function (or any other member of the returned object), is a copy created temporarily or all is resolved with the returned reference?Is it bad to have three functions, return by value, by const-reference and by reference?
// Return by value std::set<uint32_t> GetValues () const { return m_values; } // Return by const-reference const std::set<uint32_t> & GetValues () const { return m_values; } // Return by reference std::set<uint32_t> & GetValues () { return m_values; }