milchschaum
milchschaum

Reputation: 161

Using shared_ptr without name?!

I'm reading the book "Game Coding Complete" which basically is about the concept of game engines. The part about resource cache has some code I don't quite understand.

extern shared_ptr<IResourceLoader> CreateWAVResourceLoader();

where CreateWAVResourceLoader() looks like

    shared_ptr<IResourceLoader> CreateWAVResourceLoader()
{
    return shared_ptr<IResourceLoader>(GCC_NEW WaveResourceLoader());
}

and afterwards the authors register the wave resource loader

m_ResCache->RegisterLoader(CreateWAVResourceLoader());

To me, the line extern shared_ptr<IResourceLoader> CreateWAVResourceLoader(); is a little bit confusing, because I'm calling the function which returns a shared_ptr, but how can I use that pointer without a name? I'm pretty sure it's my lack of experience in C++, so please enlighten me. :)

Thanks!

Upvotes: 0

Views: 151

Answers (3)

Plecharts
Plecharts

Reputation: 311

extern shared_ptr<IResourceLoader> CreateWAVResourceLoader();

just means that the function will be implemented in another file (extern) and that it will return shared_ptr. The whole line is just a function declaration and

shared_ptr<IResourceLoader> CreateWAVResourceLoader()
{
    return shared_ptr<IResourceLoader>(GCC_NEW WaveResourceLoader());
}

is just an implementation of the function.

Upvotes: 0

Pubby
Pubby

Reputation: 53017

but how can I use that pointer without a name?

You're not the one who will be using the shared_ptr, the object m_ResCache will be. I assume that object has an interface for handling resources, and keeps track of shared_ptrs internally.

i.e. it's like this:

class foo {
  public:
    RegisterLoader(shared_ptr<IResourceLoader> ptr) { internal_ptr = ptr; }

    DoSomethingWithLoader() { /* ... */ }
  private:
    shared_ptr<IResourceLoader> internal_ptr;
};

Upvotes: 2

Qaz
Qaz

Reputation: 61910

That line is a function declaration. It is named CreateWAVResourceLoader, has no parameters, and returns a shared_ptr<IResourceLoader>.

When you say:

m_ResCache->RegisterLoader(CreateWAVResourceLoader());

That's when you call it. It passes the temporary shared pointer returned from the function into RegisterLoader.

Upvotes: 3

Related Questions