Q. Please explain: In function X, we are to have objects A, B, C declared NOT us
ID: 3912612 • Letter: Q
Question
Q. Please explain: In function X, we are to have objects A, B, C declared NOT using new and objects X, Y, Z declared using new. How do we have the lifetimes of these 6 objects all end outside of X’s scope? Why?
Q. Please explain Scott Meyers’s point: Use weak_ptr for shared_ptr like pointers that can dangle.
Q. Please explain Scott Meyers’s point: unique_ptr is a small, fast, move-only, smart pointer for managing resources with exclusive-ownership semantics.
Please solve all of them. Unless not worth it.
Explanation / Answer
Please Note: You have posted more than one Question. I have answered the first question. Please Post Separate for other Questions.
Q. Please explain: In function X, we are to have objects A, B, C declared NOT using new and objects X, Y, Z declared using new. How do we have the lifetimes of these 6 objects all end outside of X’s scope? Why?
Answer)
So what we understand here is, In function X we have objects A,B,C,X,Y,Z. A, B, C are declared NOT using new and objects X, Y, Z declared using new. Thus when we use something like:
Myclass *object = new Myclass(); the object created is on the heap as the X,Y,Z here.
On the other hand the objects created without new as:
Myclass object; will be on the stack as A,B,C here.
Now since A,B,C here is allocated on the stack here, thus A,B,C is useful as long as the function is in scope. When the functions exits the variable will vanish as stack variables are not needed outside the code.
But, X,Y,Z are declared using heap and thus would be there even when the function has exited.
Thus, these are how the lifetimes of these 6 objects get impacted on leaving the function.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.