简体   繁体   中英

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.

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.

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 :)

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.

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

复制包含向量的对象时,向量将被完全复制。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM