shared_ptr efficiency problem

V

vissermc

Examine this example:

void foobar( shared_ptr <int> y )
{
if ( y.unique() ) { ... I can recycle this object for my own purpose,
efficient! ... }
else { .. too bad, I have to create a new object ... }
}

...main(..)
{
shared_ptr <int> x ( new int(3); )
foobar(x);
}

I suspect GCC (and other compilers?) will always call the destructor of
a passed variable after the last function is called.
In this case x will be destructed after foobar is called. This means
'foobar' will hit the else-case. But it would be better (more
efficient) if a shared_ptr will destruct before the actual call (there
is no need for main to hold x any longer).
The only solution I can see is: foobar(x.release());

Anyone who sees my problem? Is there a more clean/automatic solution to
this problem?
 
M

mlimber

Examine this example:

Examine the guidelines for posting code:

http://parashift.com/c++-faq-lite/how-to-post.html#faq-5.8

Your code is replete with syntax errors etc.
void foobar( shared_ptr <int> y )
{
if ( y.unique() ) { ... I can recycle this object for my own purpose,
efficient! ... }
else { .. too bad, I have to create a new object ... }
}

..main(..)
{
shared_ptr <int> x ( new int(3); )
foobar(x);
}

I suspect GCC (and other compilers?) will always call the destructor of
a passed variable after the last function is called.
In this case x will be destructed after foobar is called. This means
'foobar' will hit the else-case. But it would be better (more
efficient) if a shared_ptr will destruct before the actual call (there
is no need for main to hold x any longer).
The only solution I can see is: foobar(x.release());

Anyone who sees my problem? Is there a more clean/automatic solution to
this problem?

Make the parameter in foobar a reference:

void foobar( shared_ptr<int>& y );

or use auto_ptr in main() instead.

Cheers! --M
 

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
473,770
Messages
2,569,583
Members
45,073
Latest member
DarinCeden

Latest Threads

Top