HetMes
HetMes

Reputation: 410

Boost shared_ptr and c++ references. What's wrong here, exactly?

The code below is to create a chain of B's, to be traversed by method f.

As presented below, the code doesn't work. Each traversal only goes one level deep.

I've learned that chain should just return a shared_ptr, but my question is why exactly this doesn't work?

#include <iostream>
#include <boost/shared_ptr.hpp>

class B
{
public:
  B()
  {
  }

  B(const B& b)
  {
  }

  B& chain()
  {
    b = boost::shared_ptr<B>(new B());

    return *b;
  }

  void f()
  {
    std::cout << this << " " << bool(b) << std::endl;

    if (b)
      return b->f();

    return;
  }

  boost::shared_ptr<B> b;
};

int main()
{
  B b0;
  B b1 = b0.chain();
  B b2 = b1.chain();

  b0.f();
  b1.f();
  b2.f();
}

Upvotes: 0

Views: 75

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409176

Because when you assign it to the non-reference variables b1 and b2, copies are made. And since you have a copy-constructor which does nothing, the member variable is not copied.

Either remove the copy-constructor, or implement it properly.

Upvotes: 2

Related Questions