Click here to Skip to main content
15,887,333 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
I am learning about smart pointers.
C++
class Elf {
private:
    int _health = 0;
public:
    Elf(const int &health){_health = health;}
    int getHealth(){return _health}
};


What is the different between these two?
First case:
C++
vector<unique_ptr<Elf>> elves;
for (auto i = 0; i < 10000; ++i) {
    elves.push_back(unique_ptr<Elf>(new Elf(90)));
}

Second case:
C++
auto elves = make_unique<vector<Elf>>(10000, Elf(90));

=========
The second question.
For the first case, I can access private member _health by this:
C++
for(auto i = 0; i < 10000; ++i){
    cout << elves[i]->getHealth() << " ";
}

How to access _health in the second case?
Posted
Updated 5-Apr-17 5:18am

Quote:
What is the different between these two?

The first is a vector of (smart) pointers to elves and the second is a (smart) pointer to a vector of actual elves.

You could compare the first to a sign pointing to a chest of drawers with an elf sitting in each drawer (basically a large house), whereas the second is a chest of drawers where each drawer contains the home address of an elf (basically an address book).

Quote:
How to access _health in the second case?

Solution 1 should work, but if you prefer code that uses the index operator (and thus is closer to the first version), try this:
C++
cout << (*elves)[i].getHealth();



P.S.:
oops, just noticed the date. I assumed it was a new request based on it's listing on the front page...
 
Share this answer
 
v2
#include <memory>
#include <vector>


class Elf {
private:
	int _health = 0;
public:
	Elf(const int &health){ _health = health; }
	int getHealth(){ return _health; }
};


void Test()
{
	using namespace std;
	auto elves = make_unique<vector<Elf>>(10000, Elf(90));

	int out;
	for (auto i = 0; i < 10000; i++)
	{
		out = elves->at(i).getHealth(); /* out = 90 */
	}	

}
 
Share this answer
 
v4
Comments
Dave Kreskowiak 5-Apr-17 9:39am    
Watch the dates on posts. This is a year and a half old.
Theo Buys 5-Apr-17 11:20am    
Time is on my side. Why nobody has aswerwerd this nice question?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900