Phoeniyx
Phoeniyx

Reputation: 572

Does std::set insert require the input object to be dynamically allocated if input object goes out of scope?

I have a question about the std::set class and scope of the input object.

Please consider the code:

#include <iostream>
#include <set>

using namespace std;

class K {
private:
    int m_a;
  ...
public:
    K(int temp) { m_a = temp; }
  ...
};

int main ()
{   
    set<K> mySet;

    for(int i=0; i<10;i++)
    {
        K a(rand());
        mySet.insert(a);
    }

    return 0;
}

Is this code ok? Since std::set.insert(.) take values by reference, don't all the "a" values inserted need to be in scope while mySet contains the "a" values? In this case, there are 10 instances of "a" with different m_a values.

In this situation, on every iteration of the for loop, the current "a" goes out of scope. Would the proper thing to do in this situation to dynamically allocate "a" as in:

for(int i=0; i<10;i++)
{
    K *a = new K(rand());
    mySet.insert(*a);
}

Of course, when mySet gets destroyed, all the inserted "a" values (of type K) should be deleted. Is what I said above accurate?

Thanks.

Upvotes: 2

Views: 146

Answers (1)

danadam
danadam

Reputation: 3450

std::set insert() method accepts arguments by const ref (at least one of its versions), but the container makes a copy of the argument internally. Your first example is ok. Actually, it is even required that the type stored in std::set has public copy constructor available (either explicit, wrote by you or implicit, generated by compiler)

Upvotes: 3

Related Questions