smart pointer

T

Tony Johansson

Hello Experts!

I reading a book called programming with design pattern revealed
by Tomasz Muldner and here I read something that I don't understand so I ask
you.

First some background below is a class ResourceHandle that is a wrapper
class.
The copy constructor and the assignment operator are private to disallow
copying of the ResourcePointer
handle. The constructor associates the handle with the pointer to Resource
and the destructor deletes this pointer. Here I can use ResourceHandle
anywhere I can use ResourcePointer.
There is also a type conversion from ResourceHandle to ResourcePointer.

Now to my question what kind of expression is this
ResourceHandle r(newResource());
What I have found it's the same as I think.
Resource* r(new Resource());
But I'm not familar with that expression either.
Is this Resource* r(new Resource()); the same as
Resource* r = new Resource();



typedef Resource* ResourcePointer;
class ResourceHandle
{
public:
ResourceHandle(const ResourcePointer& r) : handle(r) {}

virtual ~ResourceHandle()
{ delete handle; }

operator ResourcePointer() const //type conversion from ResourceHandle
to ResourcePointer
{ return handle; }

private:
ResourcePointer handle;
ResourceHandle(const ResourceHandle&);
ResourceHandle% operator=(const ResourceHandle&);
};

Many thanks

//Tony
 
G

Gianni Mariani

Tony said:
Now to my question what kind of expression is this
ResourceHandle r(newResource());

nit pick - you meant this below, right ?
ResourceHandle r(new Resource());

ResouceHandle is a class that takes Resource* as a constructor argument.
i.e. it invokes

ResourceHandle::ResourceHandle(const Resource *& r)
What I have found it's the same as I think.
Resource* r(new Resource());

Yes - however, Resource* is a POD (plain old data) type and
ResourceHandle is a class.
But I'm not familar with that expression either.
Is this Resource* r(new Resource()); the same as
Resource* r = new Resource();

Yes - these are identical, especially for POD types.

In theory, you could write :

ResourceHandle r = new Resource();

In this case, the compiler would construct a temporary ResourceHandle
(using ResourceHandle::ResourceHandle(const Resource *& r) ) and then
assign it to r using :

ResourceHandle::ResourceHandle(const ResourceHandle&)

but in this case, this is illegal since this constructor is private.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top