Sashidhar Guntury
Sashidhar Guntury

Reputation: 11

How to insert objects in a vector efficiently and correctly

Suppose I want to declare a vector of objects. I can do it this way -

vector<mynode> nodes;

But if the size of the mynode is large, this would be bad. So I think of doing it this way -

vector<mynode*> nodes;

But the above declaration has an obvious problem that I'm storing addresses and it's not safe at all. For instance, if i add objects in a foor loop -

vector<mynode*> nodes;
for (int i=0; i<10; i++)
{
    mynode mn;
    nodes.push_back(&mn);
}

This will lead to errors as I can never guarantee if the contents of the pointer are actually ok.

So, I decide to use this declaration -

vector<mynode&> nodes;
for (int i=0; i<10; i++)
{
    mynode mn;
    nodes.push_back(mn);
}

is this ok? safe? It gives a compilation with the first line itself. Please suggest some efficient way of storing the objects in a vector. thanks a lot.

Upvotes: 0

Views: 8879

Answers (3)

Alexandre C.
Alexandre C.

Reputation: 56956

I can do it this way -

vector<mynode> nodes;

But if the size of the mynode is large, this would be bad.

No, it would not. You need to store the objects anyway. If you are worried about copying large objects, you have some solutions:

  1. Use std::vector<std::unique_ptr<my_node>> (or another smart pointer), which automatically releases objects on destruction. This is the best solution if my_node is polymorphic.
  2. Use std::vector<my_node> and use the emplace_back function to construct objects in place (beware if you're using visual studio 2010, this function does not do what it is supposed to do).
  3. Still use std::vector<my_node> and use push_back with a rvalue reference, as in

    v.push_back(std::move(some_node));

    to move already constructed objects.

Anyway, a good rule of thumb is to have the copy constructor/assignment deleted (or private) for most non-lightweight objects. Containers are still functional (provided, again, that you use C++11) and your concerns are moot.

Upvotes: 3

stanwise
stanwise

Reputation: 2412

Using references gives is essentially the same as using pointers (it's just that you don't need to dereference them in code). If you want to automatically ensure that the objects inserted to vector don't get deleted without copying them, you should use smart pointers from boost or c++11.

vector< smart_ptr<mynode> > nodes;
for (int i=0; i<10; i++)
{
    smart_ptr<mynode> mn = new mynode();
    nodes.push_back(mn);
}

Upvotes: 1

dbrank0
dbrank0

Reputation: 9466

I dont see pointer being so bad here. It's not void or something. Inserting reference as in your example saves a reference to a temporary object located on a stack an this will go out of scope...

Upvotes: 0

Related Questions