isocpp / isocpp/CppCoreGuidelines

Liftetimes: shared_ptr questions

Open
#523 9 comments 0 reactions 2 assignees View on GitHub

@neilmacintosh is already working on this.

Since May 15, 2017.

open
Dominant language
CSS
Stars
45.3k
Forks
5.6k
PR merge metrics
No merged PRs in 30d

Description

I'm trying to better understand how the lifetime analysis deals with shared_ptrs. I was not able to figure out why the following program would not compile with lifetime analysis turned on.

using namespace std;
struct B;

struct A
{
        shared_ptr<B> b;
        int k;
};

struct B
{
        unique_ptr<A> a;
};

void foo(A* a)
{
        a->b->a = nullptr;
        a->k = 5;
}

void d(A* a, shared_ptr<B> b)
{
        a->b = b;
}
void g(B* b, unique_ptr<A> a)
{
        b->a = move(a);
}

int main()
{
        shared_ptr<B> b = make_shared<B>();
        auto a = make_unique<A>();

        a->b = b;
        d(a.get(), b);
        g(b.get(), move(a));
        foo(b->a.get());
}

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.