一千萬個為什麽

搜索

C ++指針,對象等

這可能有點令人困惑,但......

Let's say I have a vector type member in a class, something like vector ( I have methods on my class to return Operators from this container). Now lets say that I have a method on my class that receives an Operator object op and inserts it on the vector. What I want to know is: will I have any trouble by insert it directly into the vector (push_back(&op))? Or should I use the copy constructor to create a new Operator and then put this new one on the vector (with push_back(new Operator(op)))?

(操作員是我創建的課程)

最佳答案

Using &op only gives you a pointer to the object (which is still on the stack) and not a copy. Thus when the object goes out of scope (and gets cleaned up) the pointer in the vector becomes invalid and will cause issues.

您最好的選擇是使用上面建議的復制構造函數。

轉載註明原文: C ++指針,對象等