Q:

Why does one code produce a memory leak and the other doesn't?

Why does this code produce a memory leak? I'm a newbie and don't understand it. The object gets assigned to the shared_ptr so it's still accessible or not? I need to create the new instance in another function so I can't think of another way to do that. Is there anything I need to fix?
std::shared_ptr<MyClass>newItem(getNewMyClassInstance());

MyClass* MyClass::getNewMyClassInstance()
{
    return new MyClass();
}

Also what is the difference between the above mentioned code and
std::shared_ptr<MyClass>newItem(new MyClass());

regarding memory leaks?

A:

There is a subtle difference.
Whenever the constructor of MyClass throws, new MyClass(); does not produce any memory leak since the storage allocated for MyClass is automatically freed by new when an exception is thrown. In the snippets displayed in your question, none of the forms lead to memory leak.
But, if one would expand the definition of getNewMyClassInstance() in such a way than an exception is thrown at scope exit, your first form does lead to memory leak:
MyClass* MyClass::getNewMyClassInstance()
{
    ThrowsWhenDestructed t;
    return new MyClass();
}

std::shared_ptr<MyClass>newItem(getNewMyClassInstance());
// MyClass pointer is not acquired, and lost to oblivion.

With this form (a raw pointer returned by a function and then acquired by a smart pointer), there is a small gap where memory could be lost. Almost always this is not an issue, but it might be for you.
As an alternative, why won't you define:
std::shared_ptr<MyClass> MyClass::getNewMyClassInstance()
{
    return std::make_shared<MyClass>();
}

A:

The point I suspect that someone is making is that by returning the shared pointer, you ensure that the pointer is always wrapped by a smart pointer.  By returning a naked pointer; this guarantee is lost; and thus leaves it more open to accidental leaks; ie
 { getNewMyClassInstance()->doStuff() }

will leak in one case; but not in the other.
However; the example usage you posted will not leak.

