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.
A common pattern is to use `shared_ptr` to imply **shared ownership** and `std::unique_ptr` or even the maligned `std::auto_ptr` to convey **transfer of ownership**.

If the constructor for `A` took an `shared_ptr<B>`, then `A`'s destructor will delete the object only if there are no more shared pointers.

On the other hand, the constructor for `A` took an `auto_ptr<B>`, then the code constructing the `A` will no longer have access to the `B` pointer. So it's clear that `A` is solely responsible for its destruction now.

In both cases, the ownership is enforced by the code itself.