Getting to grips with boost::shared_ptr

  • Permalink
  • submit to reddit
  • Email
  • Follow


Hi there,

I have a class called Sounds which creates a number of Sound objects
in its constructor and adds them to a local std:map variable. I also
define an enum in this class which I use as the key with respect to
the map. This class therefore acts as a look-up for all the sounds I
wish to use.

I also have a Player class which has a Play(Sound&) function. This
function stops the currently playing sound and plays the new sound
supplied by the argument. I also have a Stop() function which stops
the current sound. I use a Sound* local variable to keep track of the
current sound.

The question is, how do I know that I shouldn't be using a shared_ptr
instead of this pointer? - a design change which would also require
storing shared_pts in the map previously mentioned. For example, I can
crash my program by deleting my Sounds object before calling
Player.Stop(). Using shared_ptrs would avoid this crash. However, this
is a reckless way of producing a crash, are there more innocent ways
in which it could occur for my Player class?

For me, it feels that my Player class does not take ownership of a
sound object; it simply keeps track of it and therefore I use a simple
pointer. Is this the correct mentality with regard to whether I should
be using a shared_ptr or a simple pointer?

Thanks very much for your help,

Barry
0
Reply Barry 3/24/2010 6:32:59 PM

See related articles to this posting


* Barry:
> Hi there,
> 
> I have a class called Sounds which creates a number of Sound objects
> in its constructor and adds them to a local std:map variable. I also
> define an enum in this class which I use as the key with respect to
> the map. This class therefore acts as a look-up for all the sounds I
> wish to use.
> 
> I also have a Player class which has a Play(Sound&) function. This
> function stops the currently playing sound and plays the new sound
> supplied by the argument. I also have a Stop() function which stops
> the current sound. I use a Sound* local variable to keep track of the
> current sound.
> 
> The question is, how do I know that I shouldn't be using a shared_ptr
> instead of this pointer? - a design change which would also require
> storing shared_pts in the map previously mentioned. For example, I can
> crash my program by deleting my Sounds object before calling
> Player.Stop(). Using shared_ptrs would avoid this crash. However, this
> is a reckless way of producing a crash, are there more innocent ways
> in which it could occur for my Player class?
> 
> For me, it feels that my Player class does not take ownership of a
> sound object; it simply keeps track of it and therefore I use a simple
> pointer. Is this the correct mentality with regard to whether I should
> be using a shared_ptr or a simple pointer?

It's OK.

Consider that the same problems that you envision exist with nearly all kinds of 
objects in C++. To avoid the /possibility/ of dangling pointers every object 
would have to be allocated dynamically and managed through smart pointers and/or 
garbage collection. If that is what one wants then some other language, e.g. 
Java or C#, is a more practical answer  --  it's not the C++ way.


Cheers,

- Alf
0
Reply Alf 3/25/2010 9:36:48 AM

Barry <bg_ie@yahoo.com> wrote in news:efac0ea9-d335-42da-8b92-
cf773ad3718e@q23g2000yqd.googlegroups.com:

> Hi there,
> 
> I have a class called Sounds which creates a number of Sound objects
> in its constructor and adds them to a local std:map variable. I also
> define an enum in this class which I use as the key with respect to
> the map. This class therefore acts as a look-up for all the sounds I
> wish to use.
> 
> I also have a Player class which has a Play(Sound&) function. This
> function stops the currently playing sound and plays the new sound
> supplied by the argument. I also have a Stop() function which stops
> the current sound. I use a Sound* local variable to keep track of the
> current sound.
> 
> The question is, how do I know that I shouldn't be using a shared_ptr
> instead of this pointer? - a design change which would also require
> storing shared_pts in the map previously mentioned. For example, I can
> crash my program by deleting my Sounds object before calling
> Player.Stop(). Using shared_ptrs would avoid this crash. However, this
> is a reckless way of producing a crash, are there more innocent ways
> in which it could occur for my Player class?
> 
> For me, it feels that my Player class does not take ownership of a
> sound object; it simply keeps track of it and therefore I use a simple
> pointer. Is this the correct mentality with regard to whether I should
> be using a shared_ptr or a simple pointer?

Yes, the only thing shared_ptr does is to keep the object alive until it is 
not needed any more. If you are not deleting any Sound anyway before the 
end of the program, then you do not need shared_ptr. OTOH if you foresee 
that you might want sometimes to delete a Sound in the middle of the 
program, for example by replacing it with an updated version loaded from 
disk, then shared_ptr would probably be the simplest way to achieve this 
feature.

cheers
Paavo
0
Reply Paavo 3/26/2010 7:54:30 AM
comp.lang.c++ 48427 articles. 31 followers. Post

2 Replies
204 Views

Similar Articles

[PageSpeed] 12/16/2014 11:59:51 AM


  • Permalink
  • submit to reddit
  • Email
  • Follow


Reply:

Similar Artilces:

#include <boost/shared_ptr.hpp> or #include "boost/shared_ptr.hpp"?
Is there a general rule/convention for when to use angle brackets and when to use quotes in #include statements? Is the angle bracket reserved for "system" header files (e.g. standard library headers), or is it for general "stable" include files? What about the grey areas in between these and actual application code, e.g. headers for a library that is under my control but external to the project being compiled? I know both styles work, and in the case of the Boost headers I've seen both of them used in example code, I'm just wondering if one is more "c...

tr1::shared_ptr and boost::shared_ptr
What was the justification for the tr1 shared_ptr not to allow a custom deleter like the boost::shared_ptr? --- [ comp.std.c++ is moderated. To submit articles, try just posting with ] [ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ] [ --- Please see the FAQ before posting. --- ] [ FAQ: http://www.comeaucomputing.com/csc/faq.html ] Axter wrote: > What was the justification for the tr1 shared_ptr not to allow a custom > deleter like the boost::shared_ptr? > There is none. It's part of the T...

lack of implicit casting to T* and boost::shared_ptr::get()
Does anyone know the reasons for the lack of an implicit casting operator in any greater depth than: A. Automatic conversion is believed to be too error prone. (from the FAQ at the bottom of: http://www.boost.org/libs/smart_ptr/shared_ptr.htm) Can anyone say specifically what about the implicit conversion would be dangerous? I can think of a few things that would require care about usage of smart pointers with implicit conversions, but nothing that I would consider 'error-prone'. In any language, there are implications and C++ certainly has its fair share of other implicit behavio...

What are the differences between std::shared_ptr and boost::shared_ptr?
What are the differences between std::shared_ptr and boost::shared_ptr? I just know they are, but don't know where. Thanks. * Kai Wen, on 14.09.2010 04:02: > What are the differences between std::shared_ptr and boost::shared_ptr? > I just know they are, but don't know where. > Thanks. Mostly none (except for the namespace), because std::shared_ptr was adopted from boost::shared_ptr. There may be a difference with respect to custom deleter replacement, and perhaps with respect to conversions and perhaps also iostream operator<< support, that is, that pe...

What are the differences between std::shared_ptr and boost::shared_ptr? #2
I just know they are, but don't know where. Thanks. ...

Problems mixing boost::lambda::bind and boost::shared_ptr..
Hi, Consider the following: class A { public: virtual bool foo() = 0; }; class B : public A { public: virtual bool foo() { return false; } }; void fn() { std::list< A * > aList(10); std::list< boost::shared_ptr<A> > aSharedList(10); // This works fine.. std::count_if( aList.begin(), aList.end(), boost::lambda::bind(A::foo, boost::lambda::_1) ); // This doesn't compile.. std::count_if( aSharedList.begin(), aSharedList.end(), boost::lambda::bind(A::foo, boost::lambda::_1) ); } -- Why doesn't the second ...

gets gets
I'm a little surprised at this. In irb, I tried puts gets gets. Why? I don't know. but basically, gets gets, seems to almost act like a heredoc! myString = gets gets puts myString On Mar 26, 2007, at 3:17 AM, John Joyce wrote: > I'm a little surprised at this. > In irb, I tried puts gets gets. > Why? I don't know. > but basically, gets gets, seems to almost act like a heredoc! > myString = gets gets > puts myString It's not surprising at all. First, let's insert the parentheses so we can see it as Ruby does: puts(gets(gets())) Now we see th...

Get a grip
news:1109410871.2549642d5e49f40addbdb8eb5341c62a@1usenet -- Dr. Harvie Wahl-Banghor <harvie_wahl-bangor@mindless.com> gets a taste of his own medicine and squeals: "You pathetic fag, you have to not only typo pounce but edit it out of context. What a fucking lame ass bitch." ...

OSS awareness gets get healthy boost in South Africa
OSS gets the Shuttleworth treatment Jason Norwood-Young May 12 2004 - Public awareness of open source software is due to get a healthy boost in South Africa over the next two years, thanks to the efforts of Mark Shuttleworth, The Shuttleworth Foundation, HP and the CSIR. [...] "If nothing else, we hope to educate typical computer users about what open source is," says Black. "Currently, end-users associate computers with proprietary software because they've never known any different - it's a very difficulty association to break. Open Source software is such a differe...

boost::shared_ptr and polymorphism
Hi, Is boost::shared_ptr polymorphic? i.e., can i do safe downcasting using dynamic_cast? Thanks. bb wrote: > Is boost::shared_ptr polymorphic? > > i.e., can i do safe downcasting using dynamic_cast? Why ask? Why not just try and see FCOL? :-) bb wrote: > > Is boost::shared_ptr polymorphic? > > i.e., can i do safe downcasting using dynamic_cast? > Almost. dynamic_cast itself won't work, because the compiler doesn't now about the internals of shared_ptr. But you can use dymamic_pointer_cast, which applies dynamic_cast to the stored pointer: #i...

why boost:shared_ptr so slower?
I've just done a performance test on the shared_ptr compared to the native pointer case, the results show at lease 3 times slower when the iteration number > 10000, this is the code snippet: #include <vector> #include <iostream> #include <boost/shared_ptr.hpp> using namespace std; using namespace boost; class Thing { public: Thing() { } void method (void) { int i = 5; } }; typedef boost::shared_ptr<Thing> ThingPtr; void processThing(Thing* thing) { thing->method(); } //loop1 and loop2 test shared_ptr in the vector container void loop1(long lon...

Race in boost::shared_ptr?
Is it only me who thinks that there is a race? Here is a piece of code from boost_1_41_0\boost\smart_ptr\detail \sp_counted_base_solaris.hpp, it implements simple reference counting with basic-thread safety: void release() // nothrow { if( atomic_dec_32_nv( &use_count_ ) == 0 ) { dispose(); weak_release(); } } $man atomic_ops NOTES Atomic instructions ensure global visibility of atomically- modified variables on completion. *In a relaxed store order system, this does not guarantee that the vis...

Implementation of shared_ptr in boost
While looking at the internal implementation of shared_ptr<> I found the quoted function use_count(). What I don't understand is the following What is the rational of the static_cast in it? Has it something to do with avoiding to cache that value? How is this different to simply returning the member use_count_? Thanks for any explanations Ali namespace boost { namespace detail{ class sp_counted_base { private: long use_count_; // #shared public: long use_count() const // nothrow { return static_cast<long const volatile &>( use_count_ )...

Doubt about boost shared_ptr
Hi all, I have a query regarding the exchanging of a boost::shared_ptr beween different threads. In my program i've two threads both of which having their own internal queues for storing the shared_ptr. one thread is meant to pass the shared_ptr to another after its processing. So when a message arrives i convert it into a class of my own called 'Msg' and i put the 'Msg' object pointer into a shared_ptr and put into the other thread's message queue. in that second thread after starting the processing suddenly the program stops responding. wh...

How to get boost date_time?
I have downloaded boost throught synaptic to Ubuntu 7.04. But I don't have the folder date_time in my /usr/inculde/boost dir. How do I get date_time? desktop wrote: > I have downloaded boost throught synaptic to Ubuntu 7.04. But I don't > have the folder date_time in my /usr/inculde/boost dir. How do I get > date_time? you are OT. anyway, sudo apt-get install libboost-date-time-dev Regards, Zeppe On 14 Jun, 11:58, desktop <f...@sss.com> wrote: > I have downloaded boost throught synaptic to Ubuntu 7.04. But I don't > have the folder date_time in my /usr...

GET YOUR MORNING BOOST
http://tinyurl.com/7xl3xey http://www.ebay.com/itm/251080697697?ssPageName=STRK:MESELX:IT&_trksid=p3984.m1555.l2649 ...

question about boost::shared_ptr
I am asking this question here because I did search for a boost NG but couldn't find one. My question is this: Say I have something like boost::shared_ptr<Base_Class> null_ptr; boost::shared_ptr<Base_Class> test_ptr( new Derived_From_Base_Class ); vector<boost::shared_ptr<Base_Class> > test_vector; test_vector.push_back( test_ptr ); how would I go about explicitly removing the object test_ptr points to? Would something like this work? test_vector[0] = null_ptr; test_ptr.reset(); If I manually call the dtor (something I have been warned should almost never be do...

Getting to grips with cookies
Hi all. I have never used cookis on my website. I am trying to test for a cookie and if one is not there set one. I can see all my IE cookies together with the date. I am deleting the cookie each time and a new one is added with the latest time against it. The problem is the value of the cookie is not changing as it should. Any sugestions on this. It does work in FF, but not in IE8 *** Code *** <?php if (isset($_COOKIE['History'])) { echo ("Cookie = " . $_COOKIE["History"]); } else { $time = time(); setcookie("History", $time); echo $time; } ?...

boost::shared_ptr
If a method is declared to return a type boost::shared_ptr<sometype>, how can the method be changed to do the equivalent of returning NULL when it was declared to return a raw pointer? * Christopher: > If a method is declared to return a type boost::shared_ptr<sometype>, > how can the method be changed to do the equivalent of returning NULL > when it was declared to return a raw pointer? Return boost::shared_ptr<sometype>(). Hm. I'm amazed about some of the questions here. Please read the manual before posting. Or at least, /glance/ at it. Cheers, &...

boost::shared_ptr revisited again
===================================== MODERATOR'S COMMENT: If your message is rejected, the notice is sent to you by the moderation software, not directly from a human. If your address is munged, you won't see it. ===================================== END OF MODERATOR'S COMMENT I have posted my news about one week ago, it still doesn't appear on the newsgroup. I'm not sure, what is reason for that -- I haven't received any answer, maybe because of my e-mail address was spammers-protected (although my post contained signature with way of decoding my ...

Getting to grips with the fsi
G'day Here's a newbie question from an old hand... I've done very little with D3/NT previously. All the real work seems to be done on *nix. Anyway. Be that as it may... I'm writing some software that will use a large static data file. The VME I have is way too small for it so I am getting into creating and using an fsi file for the first time. The question is : How do I do it? ;-) I've used the File Manager to create a domain and created a table within it. Not sure I've done it right so far - kind of feeling my way here. I can't seem to find any re...

Getting to Grips with Vista
Message-ID: <foipmt$9tb$01$1@news.t-online.com> [quote] I myself run W2K in a virtual machine, and it is my base windows install which I use for all windows development (which now mainly is compiling and debugging on it. *Writing* the stuff is done on linux, in KDevelop The poor WinXP laptop gets switched on very rarely, to test if all stuff runs OK on XP too (it *does* happen that the two react slightly different, and it is difficult to find and program around if they do) In my opinion, W2K was the best windows ever, far better than XP, and not to mention this garbage they named Vista...

Getting to grips with Linux
Nice BBC article for you to comment on. Balanced and says pretty much what anyone with common sense and a feeling for real peoples need say. http://news.bbc.co.uk/1/hi/technology/7594249.stm ,---- | First impressions of Linux were positive. The new machine, an Asus Eee, | came pre-installed with a distribution, or flavour, of Linux called | Xandros. `---- ,---- | The music management program - its "iTunes", if you like - let me listen | to music and podcasts on my new laptop but wouldn't sync anything I | loaded on to my iPod. Big problem for a music and podcast junkie. `--...

Getting to grips with SATA
I got a Maxtor 120Gig SATA HDD, boots up fine when it's the only drive on my computer. The BIOS (Award) is set to HDD-0. Now, I'd like to install my old 60Gig Seagate as a Slave (was the Master) so I can access the data. I set the jumpers on it for Slave operation, but booting up the computer fails when the Seagate is attached. It seems to want to boot from the old drive, even though it is set as Slave. I tried cabling it up to the primary, and also tried secondary IDE header, as HDD-1 and various other selections, to no avail. I downloaded and installed the last BIOS upg...