Bloomberg LP Interview Question Software Engineer / Developers

  • bloomberg-lp-interview-questions
    0
    of 0 votes
    2
    Answers

    why do we need weak_ptr? give an example by code!

    I didn't answer the question well.

    I am really confused about weak_ptr. weak_ptr is an observer of shared_ptr, meaning that we always need shared_ptr in order to use weak_ptr. but in cyclic case, we don't use shared_ptr for one of the object, then in this case how can we use weak_ptr without shared_ptr to break cycle?

    - Itcecsa on April 06, 2012 in United States Report Duplicate | Flag
    Bloomberg LP Software Engineer / Developer C++

Country: United States
Interview Type: In-Person


Comment hidden because of low score. Click to expand.
2
of 2 vote

We need to use weak_ptr to avoid cycles in data structures. weak_ptr points to a resource which is managed by one or more shared_ptr. As the weak_ptr does not effects the resource reference count(weak_ptr holds weak or non-owning reference) so when the last shared_ptr object that manages that resource is destroyed the resource will be freed even if the resource is pointed by a weak_ptr. For the cycle problem think about a circular link list. Where, if every node holds the shared_ptr which owns the next node will never be freed because none of the reference count can be zero. To avoid this problem, if the last node hold weak_ptr object of the first node, then the first node can be destroyed even it is pointed from the last node.

- Palash on April 07, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I like the example from Josh Block in Effective Java: An object cache uses weak_ptr while the users hold a shared_ptr. This avoids caching objects indefinitely.

- Vick on May 04, 2012 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book walking you through every aspect of getting a job at a top tech company, while focuses on software engineering interviews.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More