Question: Sometimes when an object is created with a pointer to another object, this means it is responsible for destroying the other object on destruction... other times it is not. Sometimes there are even cases where it can vary depending on circumstances, rather than fixed rules for each class.

Very simple example:

```
class A
{
private:
 B *b;
public:
 A(B *_b)
 {
  if(_b)b = _b; //A should NOT destroy b
  else b = new B(); //A should destroy b
 }
}

```

In `A::~A()` you then end up needing to know. Of course you could have a little boolean flag but I wondered if there is any well-used pattern here? Or even a name of this behavior I can put in code comments so another developer will have more of a clue?

Answer: 
The general idea is called "Smart Pointer", in your specific example, you need a shared\_ptr.

```
class A {
  std::shared_ptr<B> b;
public:
  A(std::shared_ptr<B> b = std::make_shared<B>())
    : b(b) {}
};

```

Note that you have to use boost::shared\_ptr if std::shared\_ptr is not available on your compiler.
You could handle this with two pointers, one smart, one dumb:

```
class A
{
private:
    B *b;
    std::unique_ptr<B> ub; 
public:
    A(B *_b)
    {
        if(_b)
            b = _b;
        else
        {
            ub.reset(new B);
            b = ub.get();
        }
    }
};

```

Within the class, you would deal with the object through the dumb pointer, but the unique\_ptr would be responsible for its lifetime if a null pointer was passed in.