c++ - Why returning a std::vector is still making a copy? -
i have class going create pretty big array of data don't want copied around. considerations, immutable (read only) outside class.
here's concept code shows how want implement it:
class c { public: c(); std::vector<int> const& get_vector() { return m_vector; } private: std::vector<int> m_vector; }; c::c() { m_vector.push_back(1); m_vector.push_back(2); } void displayvector(std::vector<int> const& new_v) { (int = 0; i<new_v.size(); i++) std::cout << new_v[i] << std::endl; } int _tmain(int argc, _tchar* argv[]) { c myobj; std::vector<int> v = myobj.get_vector(); v.push_back(3); displayvector(v); }
when step through code, see given memory address m_vector , first element of array (using begin iterator).
when return get_vector, vector "v" , first element have different memory address. v.push_back(3) doesn't have problem modifying v (since looks it's copy)
when call displayvector, works expected , new_v addresses same main v.
what doing wrong?
you explicitly created copy with
std::vector<int> v = myobj.get_vector();
which can modify since v
is plain vector<int>
. here v
got copy-constructed.
to instead bind reference (which has const
because of get_vector
's return type) use
const std::vector<int>& v = myobj.get_vector();
or just
const auto& v = myobj.get_vector();
Comments
Post a Comment