dimanche 25 février 2018

Different address after struct initialization

I'm looking at this simple struct:

struct Journal
{
  std::string title;
  std::vector<std::string> entries;

  explicit Journal (const std::string& title): title(title)
  {
    std::cout << "Address of title is " << &title << std::endl;
  }

  void add(const std::string& entry)
  {
    std::cout << "Address of title is " << &title << std::endl;
    entries.push_back(entry);
  }
};

int main() {
  std::string title = "Hello";
  std::string entry = "World";

  std::cout << "Address of title is " << &title << std::endl;
  Journal *journal = new Journal(title);

  (*journal).add(entry);
  std::cout << journal->entries.front() << std::endl;
  return 0;
}

I always thought the address of title should be the same through the whole execution, however, I was wrong as I got the following output:

Address of title is 0x7ffee90d3978
Address of title is 0x7ffee90d3978
Address of title is 0x7fa86f402740
World

Can somebody explain what happened after the initialization? Why would I get a different address? Does that mean a copy happened?

Aucun commentaire:

Enregistrer un commentaire