lundi 29 octobre 2018

What's the difference between returning a const object reference (getter), and just the string?

I was going through the c++ website tutorials as a nice compliment to a college course I'm taking this semester (beginner). While learning about copy constructors and destructors, I came across this section of code:

// destructors
#include <iostream>
#include <string>
using namespace std;

class Example4 {
    string* ptr;
  public:
    // constructors:
    Example4() : ptr(new string) {}
    Example4 (const string& str) : ptr(new string(str)) {}
    // destructor:
    ~Example4 () {delete ptr;}
    // access content:
    const string& content() const {return *ptr;}
};

int main () {
  Example4 foo;
  Example4 bar ("Example");

  cout << "bar's content: " << bar.content() << '\n';
  return 0;
}

Now, I understand the destructor part, but the getter for the string member confused me. Why return a reference (alias) to the object (string in this case)?

// access content:
const string& content() const {return *ptr;}

What is the difference between that, and just returning the string?

string content() const {
    return *ptr;
}

Is returning a const alias more efficient? Are you returning just the address of the string, or the string itself? What about when just returning the string, are you returning the entire string? Thanks.

Aucun commentaire:

Enregistrer un commentaire