views:

134

answers:

6
+1  Q: 

About C++ pointers

I am curious to how data is handled in the situation:

chapterlist.clear();
cScene newscene;
newscene.name = "Laura does something.";
newscene.words = 432;
newscene.pov = "Laura";
cChapter newchapter;
newchapter.scenelist.push_back(newscene);
chapterlist.push_back(newchapter);

chapterlist is a cChapter vector.

I am creating a new cScene object, and pushing it onto the scenelist vector of a new cChapter object, which I then push onto chapterlist.

My question is: when I am pushing objects onto a vector, is all the data being duplicated into the vector, while the old data is destroyed from the stack when the scope ends?

Or is something else happening???

PS: I hate pointers, as do many.

+5  A: 

When you push something into vector the object is copied using a copy constructor. The initial object lifetime will be completely disconnected from the lifetime of the object constructed inside the vector.

sharptooth
+1  A: 

And when you copy an object containg a vector the vector is copied entirely.

Anton Petrov
+4  A: 

My question is: when I am pushing objects onto a vector, is all the data being duplicated into the vector, while the old data is destroyed from the stack when the scope ends?

Yes.

PS: I hate pointers, as do many

Well try not too, memory is just a huge array of bytes :) Pointers are just indexes into that huge array. When you get your head round them you will laugh at just how simple they are :)

Goz
+2  A: 

Assuming you have something like

struct cScene {...};
struct cChapter {
    std::vector<cScene> scenelist;
}

then no pointers are involved at all, and entries pushed onto scenelist will be copied, every element in scenelist will be destructed when cChapter is.

If you had

struct cChapter {
    std::vector<cScene*> scenelist;
}

and used

cScene * newscene = new cScene;
newchapter.scenelist.push_back(newscene);

then the pointer is copied, so you now have two separate pointers to the same memory location, with all the management of lifetime that entails. If the cScene elements are large and you don't want the copy overhead of std::vector, have a look at boost's smart pointers

Scott Wales
cScene and cChapter are classes, not structs. Does this change anything?
Alexander Rafferty
@Alexander No, `struct foo{...};` is entirely equivalent to class `foo{public: ...};`.
Scott Wales
+3  A: 

The C++ standard states in chapter 23, Containers library that a.push_back(x) has the operational semantic a.insert(a.end(), x). It is furthermore stated that a.insert(p, t) inserts a copy of t before p.

So yes, a copy is inserted into the vector.

Jim Brissom
+1  A: 

The answer to your question is yes : The original data will be copied in a new structure inside the vector and will then be destroyed at the end of the stack.

But don't worry too much. Here, you use a structure that is pretty slim : two char pointers and one integer. You should be fine copying it.

Benoît