// Ex10_03.cpp
// Storing pointers to objects in a vector
#include <iostream>
#include <vector>
#include <memory>
#include "Person.h"
using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::shared_ptr;
using std::unique_ptr;
using std::make_shared;
int main()
{
vector<unique_ptr<Person>> people; // Vector of Person object pointers
const size_t maxlength(50);
char firstname[maxlength];
char secondname[maxlength];
while(true)
{
cout << "Enter a first name or press Enter to end: ";
cin.getline(firstname, maxlength, '\n');
if(strlen(firstname) == 0)
break;
cout << "Enter the second name: ";
cin.getline(secondname, maxlength, '\n');
auto pPerson = unique_ptr<Person>(new Person(firstname, secondname));
people.push_back(std::move(pPerson));
//people.push_back(unique_ptr<Person>(new Person(firstname, secondname)));
pPerson->showPerson();
}
// Output the contents of the vector
cout << endl;
for(auto& p : people)
p->showPerson();
cout << endl << " and again..." << endl;
for(auto& p : people)
p->showPerson();
// Pointers in the people vector are now invalid
// so remove the contents
people.clear();
return 0;
}
On line 45 and 46 it says the pointers are now invalid so remove the contents?
How are they invalid? Also when you call people.clear, the smart pointers also delete the person objects right?
Based on what I'm seeing, I think the author of the code meant that from the call to people.clear( )" and onwards, all elements of "people" are to become invalid.
Anmol444 wrote:
"Also when you call people.clear, the smart pointers also delete the person objects right?"
Yes. The last time I checked, safe-pointers free the memory they own within their own destructor, so when "people.clear( )" is called, each destructor of each safe-pointer is called, thereby freeing the memory held by each safe-pointer; thus, invalidating each element of "people".
Just a really minor thing - why can't you use std::string instead of char arrays?
std::string has a lot of good stuff in it - like the == operator - use instead of strcmp, for example. And you have access to all the algorithms as well.