Using typedef with raw pointer vs. shared_ptr

c++, shared-ptr, typedef

Solution

So, why does the first `typedef` work fine but the second one does not?

Because your first `typedef` forward-declares `Node`:

typedef struct Node* NodePtr;
//      ^^^^^^^^^^^

You could do the same in the second `typedef`:

typedef std::shared_ptr<struct Node> NodePtr;

If you want to avoid it, declare the typedef inside the structure:

struct Node {
    typedef Node* ptr; // no need for `struct`!
    // or `typedef std::shared_ptr<Node> ptr;`
    int data;
    ptr next;
};

Also, since this is C++11, you can use `using` instead of `typedef`:

using ptr = Node*; // vs. `using ptr = std::shared_ptr<Node>`

Problem

Here's an example of a linked list `Node` struct containing an `int data` and a `NodePtr next`. My idea is to use a `typedef` for the `NodePtr` because I want to experiment with a raw pointer vs. a shared_ptr. Also, to keep it simple, I want to be able to change just a single line to go from one to the other. With raw pointers, the following code compiles just fine. ``` typedef struct Node* NodePtr; struct Node { int data; NodePtr next; }; ``` But if I simply change the typedef to a shared_ptr, I get compilation errors. ``` typedef std::shared_ptr<Node> NodePtr; struct Node { int data; NodePtr next; }; error: ‘Node’ was not declared in this scope error: template argument 1 is invalid ``` I can fix this by making a forward declaration of `Node`. However, the double definitions of `Node` look a bit ugly to me. ``` struct Node; typedef std::shared_ptr<Node> NodePtr; struct Node { int data; NodePtr next; }; ``` So, why does the first `typedef` work fine but the second one does not? And, is it possible to `typedef shared_ptr`s without using a forward declaration?

Original source