WhatABeautifulWorld
WhatABeautifulWorld

Reputation: 3388

Return reference to private member

I have a class

class SomeClass {
  public:
    using DType = std::vector<int>;

    DType& data1() {   // this should return a reference to data
      return data;
    }

    DType data2() {   // this should return a copy to data
      return data;
    }

  private:
    DType data;
}

My understanding is, if I do

SomeClass temp;
auto d1 = temp.data1();  // this should NOT do any copying just create a new ref
auto d2 = temp.data2();  // this supposed to copy the data?

I am reading a book and it says when I do

auto d1 = temp.data1()

It will make a copy of the whole data and assign to d1... Does the book make any mistake?

* * * ************ updated from reading other's answer *****************

It seems "auto" is doing something funny here. I guess if I do:

std::vector<int>& d1 = temp.data1() . // this is not copying

But if I do:

std::vector<int> d1 = temp.data1() . // this is copying

Upvotes: 1

Views: 602

Answers (1)

David Schwartz
David Schwartz

Reputation: 182819

Your understanding is incorrect. auto d1 = temp.data1(); will make a copy. If you want a reference, use auto& d1 = temp.data1();.

Upvotes: 5

Related Questions