Kinda confused if I'm going about this exercise right.
- Write a function that returns a dynamically allocated vector of ints.
- Pass that vector to another function that reads the standard input to give values to the elements.
- Pass the vector to another function to print the values that were read.
- ...use shared_ptr.
#include <iostream>
#include <vector>
#include <memory>
usingnamespace std;
shared_ptr<vector<int>> setVec()
{
shared_ptr<vector<int>> pv = make_shared<vector<int>>();
return pv;
}
void readVec(shared_ptr<vector<int>> pv2)
{
int x;
while (cin >> x)
{
pv2->push_back(x);
}
}
void printVec(shared_ptr<vector<int>> pv3)
{
for (auto x : *pv3)
{
cout << x << endl;
}
}
int main()
{
shared_ptr<vector<int>> hold = setVec();
readVec(hold);
printVec(hold);
return 0;
}
I don't really understand the dynamically allocated part, I only understand that that term is used when referring to objects that's created via new or make_shared. Does that mean that the object is temporary and can only exist as long as there are pointers pointing to it?
Also I'm not sure about my use of shared_ptr. Generally, am I doing it right? Is this necessary?
shared_ptr<vector<int>> hold = setVec();
I guess so since all the other pointers die off after their scope ends.
No. It means that the object has a dynamic storage duration, and will exist till the deleter is invoked.
> and can only exist as long as there are pointers pointing to it?
When the life-time of last shared pointer pointing to it expires, the destructor invokes the deleter, thereby ending the life-time of the pointed object.
> Generally, am I doing it right?
Yes.
> Is this necessary? shared_ptr<vector<int>> hold = setVec();
With readVec() having a void result type, Yes.
You can avoid it if the program is written this way:
Thanks for the clarification and of course the alternate solution. So if the object requires a destructor to delete it (and I understand that I'll have to explicitly request a delete on regular pointers for the same effect):
1 2 3
int *q = newint(42), *r = newint(100);
r = q;
What happens to the object that r was pointing to?
It's just a follow up exercise and I was curious about the technical answer behind it. Sorry if the title mislead you, didn't think that for that question it needed another thread. Thanks for the help everyone.
Sorry it's 7am atm. Do you mean I could have completed the exercise using references or the way I wrote the code could have been replaced with references and would work just the same?
If it's the second, does JLBorges's example show a proper use case for shared_ptr?