Reputation: 303
Suppose I need to create a heap allocated container from another container. Does the initial container need to be also heap-allocated, or are its values implicitly copied into the heap, and hence the original container can just be a local variable? Example:
list<int> my_function()
{
set<int> my_set;
my_set.insert(1);
my_set.insert(2);
list<int> *my_list = new list<int>(my_set.begin(), my_set.end());
return *my_list;
}
versus
list<int> my_function()
{
set<int> *my_set = new set<int>;
my_set->insert(1);
my_set->insert(2);
list<int> *my_list = new list<int>(my_set->begin(), my_set->end());
return *my_list;
}
Which of the above is correct? I want to avoid duplicating heap-memory without my knowledge, of course.
Upvotes: 0
Views: 614
Reputation: 22991
This would be correct:
list<int> my_function()
{
set<int> my_set;
my_set.insert(1);
my_set.insert(2);
return list<int>(my_set.begin(), my_set.end());
}
I am not sure what you mean with "heap allocated", but keep in mind, that list
and set
already store data on the heap.
Upvotes: 2