Getting to grips with boost::shared_ptr

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
Barry
3/24/2010 6:32:59 PM
comp.lang.c++ 48809 articles. 0 followers. Post Follow

2 Replies
233 Views

Similar Articles

[PageSpeed] 8/2/2015 5:45:30 PM
* 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
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
Paavo
3/26/2010 7:54:30 AM
Reply:
Similar Artilces:

FAQ - Etiquette
There are several FAQs about the Oracle database scattered around the Internet, and many ways of finding answers to the simpler questions about Oracle very quickly. The following list is a suggestion of where you might find answers to questions that you feel should have an easy answer. The Co-operative Oracle Users' FAQ http://www.jlcomp.demon.co.uk/faq/ind_faq.html The archive for this news group http://www.google.com select the GROUPS tab then work through the list to comp -> databases -> oracle A search engine for searching the manuals for current versions...

How to get a vendor to listen to you
I don't know how much of this is true or just conjecture, but it does paint an interesting picture about how to get support for a platform, despite political repercussions. Yousuf Khan http://www.theinquirer.net/?article=12797 ...

Spammer getting through my NAT router?
I have a home network that I thought was pretty secure. It uses an old Macintosh running the NAT program IPNetRouter. Sometimes I use the FTP or web server function of IPNetRouter, but fortunately no one writes viruses for old out&#8211;of-date Macs these days and I have never had a problem. These are currently turned off. I am upstairs running Windows XP with ZoneAlarm Pro (mostly to check for anything I don&#8217;t know about going out). I was surprised to find a few rare cases of ICMP packets coming in from the outside and reaching my PC. Most of these were responses to pings initi...

How to get combinations of a matrix
hello, I have R=[ 0 1 1 0 ] means 2 number are there and 4 places in R. I need 16 different R combinations. can anyone help me??? Thanks Ankur Ankur Garg wrote: > > > hello, > > I have R=[ 0 1 1 0 ] > means 2 number are there and 4 places in R. > > I need 16 different R combinations. > > can anyone help me??? > > Thanks > Ankur I'm not sure if I've understood your assignment properly, but this gives an interesting output that might be sort of what you want. str2num(reshape([reshape(dec2bin(0:15)',1,64); char(ones(1,64)*32)],8,16)') ...

How could I get two desktop Macs in two apartments of the same building to share the same contents?
How could I get two desktop Macs in two apartments of the same building to share the same contents, so that if I change the contents of one computer, the changes are reflected in the other computer? I would be the only person operating the computers. In both apartments I want to operate printers connected to the desktop Macs. I have an Airport Extreme and an Airport Express already hooked up to my existing Mac, so I'm wondering how I could extend my network into the second apartment, which is in a different apartment of the same building. Robert On 2013-03-18, Robert Montgo...

Get the pid of a os.startfile(filename)
Hi to all, How can I get the Process ID (PID) of an application started because of os.startfile(filename)? Or, better, How can I get the PID of a running program, suposing I know the name of the running application? Many thanks. Daniel Hi ! With W2K or WXP : tasklist /FI "IMAGENAME eq exename.exe" And, with Python, how capture this information : def findPID(exename): import os a = os.popen4('tasklist /FI "IMAGENAME eq '+exename+'"') a[0].flush() try: info=a[1].readlines()[3].split() except: info=[exename...

I Keep Getting and "unknown database" error when I open my program that is using Flashfiler
Hi, I have been using AccuEvents for my entertainment company over the past= 6 years or so. I'm not very good working with this Flashfiler server, so = I try not to make changes. However, due to a problem with one of the compu= ters on my network tried to make changes for the software to work. Now I k= eep getting an "unknown database" error when I open up the software after I= 've started the server. I have gone both thru the tcpi/int and single serv= er steps, but it keeps coming back with "unknown database". Can someone he= lp me solve this? Al...

sort and get index?
In matlab, the sort function returns two things: [a,b]=sort([5, 8, 7]) a = 5 7 8 b = 1 3 2 where a is the sorted result, and b is the corresponding index. Is there C++ code available to achieve this? Better compatible with STL vector. Thanks "b83503104" <b83503104@yahoo.com> wrote... > In matlab, the sort function returns two things: > > [a,b]=sort([5, 8, 7]) > > a = 5 7 8 > b = 1 3 2 > > where a is the sorted result, and b is the corresponding index. > Is there C++ code available to achieve this? Probably. You co...

Cannot get PiCTeX to process an example file.
Hi All, I bought the PiCTeX manual from PCTeX and copied the LaTeX code (see below) from page 71 of the manual. I guarantee there are no typos in my copying. I also bought the LaTeX CD from TeXnicCenter and use PiCTeX which came on that CD. When I run the code below through the LaTeX compiler from TeXnicCenter I get the errors: ! Undefined control sequence. <argument> \fiverm l.2566 \setplotsymbol({\fiverm .}) ! Undefined control sequence. <argument> \fiverm l.3102 \setshadesymbol ({\fiverm .}) ! Undefined control sequence. \ninepoint I have used TeXnicCent...

difference between chan gets / gets
Hi ! What difference between command chan gets and gets, chan puts and puts ? Many thanks ! serge_darin@mail.ru <serge_darin@mail.ru> wrote: > What difference between command chan gets and gets, chan puts and > puts ? They are supposed to be the same. puts is here for compatibility (and for those too lazy to write those extra 5 chars, like me), whereas chan is an attempt to have related functionality together in a single command. If you're old to tcl, you'll likely be used to top-level "puts", whereas if you're new to tcl, you're more likely to memo...

[telecom] Woman allegedly records own arrest, gets accused of wiretapping
Woman allegedly records own arrest, gets accused of wiretapping Massachusetts wiretapping law prohibits secretly recording police. by David Kravets May 11 2014 Ars Technica A Massachusetts woman faces charges of allegedly using a hidden mobile phone to audio-record her own suspicion-of-disorderly-conduct arrest. .... http://arstechnica.com/tech-policy/2014/05/woman-allegedly-records-own-arrest-gets-accused-of-wiretapping/ Per Monty Solomon: >Massachusetts wiretapping law prohibits secretly recording police. Can somebody explain the rationale for such laws? -- P...

getting rid of a while(1) "poll"
Typical problem where a while(1) consumes gobs of CPU. Not as straightforward (to me) to figure out how to replace it with something more CPU friendly. The overall system has three daemons: 1) suck_packets_d 2) first_order_packet_filter_and_packet_buffer_d 3) extract_interesting_packet_features_and_generate_report_d Using some sort of blocking calls in 1) or 2) seems like a bad idea, because packet volume can be high and I want to keep up with it as much as possible. I could use some help thinking this through if anyone is so inclined. C / Linux pseudocode for daemon (2) (biggest ...

Get Rich
Take advantage of a great deal ...

Process getting terminated
I am facing a very strange problem. We have a process that is getting terminated without giving any clue as to how it got terminated. There are 3 threads in the process and my logs indicate that each of them was in a waiting state when the process got terminated. I have put __try __except inside each of the top level functions being executed by the threads so that I do not miss any exception if any which might cause the process to be terminated. I hooked the ExitProcess function at the very beginning (inside winmain before the other threads are created) to figure out if any thread was ...

How get on a computer from a lan?
I have a pc IBM Netvista and I know that it's possible start it from the lan when connected at lan. Do you know a program, codes and how do it? TKS On Fri, 27 May 2005 13:17:17 -0300, Rudy <rudy@genesi.ws> wrote: > I have a pc IBM Netvista and I know that it's possible start it from the > lan when connected at lan. > Do you know a program, codes and how do it? > TKS you need a dhcp server, as well as nfs, i think that's it. should boot from net fine once you have that. -- Using Opera's revolutionary e-mail client: http://www.opera.co...

How can I get the mean of all elements of a 2D Array?
I found a VI to extract the minimal and maximal value of a array, but not the mean. Is there another possibility? Thanks Simon Use the Mean function.:smileywink: On the function palette, right at the very top, is a button called 'Search'. "Mean" is such a simple function, you should make your own. The following code works for 2D, 3D, 4D, etc. arrays. :D <img src="http://forums.ni.com/attachments/ni/170/198999/1/2Dmean.png"> (You might suggest to NI that "mean" should be made polymorphic with respect to array dimensionality.)Message Edited by alte...

How to get the function of the fitting surface?
Hi, all. I've some test data in three dimension. I can get the fitting surface by some function, e.g., the griddata function. I wanna to know whether MATLAB can get the function of the surface. If can, how to get it? Many thanks for your kind. bowlder. In article <41888f1d.47620859@news.cn99.com>, bowlder <bowlders@tom.com> wrote: > Hi, all. > I've some test data in three dimension. > I can get the fitting surface by some function, e.g., the griddata function. > I wanna to know whether MATLAB can get the function of the surface. > If can, how to get i...

How to get a Maximal Image View in a Window?
*** post for FREE via your newsreader at post.newsfeed.com *** After I resized a (image) window how can I get the image maximized to fit the window? thanks Phuoc -- _/\__/\__/\__/\__/\__/\_ www.folksfun.com -----= Posted via Newsfeed.Com, Uncensored Usenet News =----- http://www.newsfeed.com - The #1 Newsgroup Service in the World! -----== 100,000 Groups! - 19 Servers! - Unlimited Download! =----- PC HUA <home-AT-huaonline.DOT.com> wrote: > *** post for FREE via your newsreader at post.newsfeed.com *** > > After I resized a (image) window how can I ...

How can i get VSC-88 Sound Canvas
Roland don't sell that if you're not buying something else...and i don't need something else ...any clue some one got a copy or ??? anything will help <jetteb@ca.ibm.com> wrote in message news:1128096404.059323.306750@g44g2000cwa.googlegroups.com... | Roland don't sell that if you're not buying something else...and i | don't need something else ...any clue some one got a copy or ??? | http://www.edirol.it/europe/details.asp?id=12&la=UK&gid=-1&gruppo=Search%20products&code=216 ...

How can you get sshd listinening TWO or more ports simultaneously?
How can you get sshd listinening TWO or more ports simultaneously? Cash Valentine wrote: > How can you get sshd listinening TWO or more ports simultaneously? man sshd_config Scan for "Port" and/or "ListenAddress". ...

[News] Free Office Suites Get Room in Windows and Challenge Microsoft Office
Office shootout: OpenOffice.org Calc vs. Microsoft Excel ,----[ Quote ] | Although individual preferences are always a factor, chances are that, in | opting for Calc and free software, you are not putting yourself at any | functional disadvantage. In fact, depending on your exact needs, in some | ways, you may find yourself ahead. `---- http://www.linux.com/feature/119546 Calc does the maths correctly. LinuxWorld.com.au: KOffice 2 on Windows ,----[ Quote ] | The article discusses the pros and cons of porting free software to | proprietary platforms noting, "there is a communit...

getting the index while iterating through a list
Hi, While iterating through a list I'd like to know not just the current element, but also its index. Is there a better way than this: i = 0 newList = [] for element in aList: newList.append((i, element)) i += 1 Is there a more elegant way of doing this with for? And with map()? Thanks Fernando Rodr=EDguez wrote: > While iterating through a list I'd like to know not just the current el= ement, > but also its index. Is there a better way than this: >=20 > i =3D 0 > newList =3D [] > for element in aList: > newList.append((i, element)) > i +=3D 1 >...

GET, GET# and end of files
This is something I tripped over yesterday. Many of my BASIC programs have the following structure: 10 open source and target files 100 clear buffer contents 200 input from a source file, process and store data in the buffer The above step is repeated while space in the buffer is available 300 output data to a target file when the buffer is full. continue at lines 100 to 300 until all data in the source file has been processed. 400 endjob processing when an end of the source file is detected. Most programmers begin line 200 with code that looks like ...

Get path
How would I get the path of the java project file or were ever the java program is running from inside the program? "Nick" wrote: > How would I get the path of the java project file or were ever the > java program is running from inside the program? Ask your teacher and this has nothing to do with GUIs. Nick wrote: > > How would I get the path of the java project file or were ever the java > program is running from inside the program? This is a little OT, isn't it? ;) You can get the URL of a resource using Class#getResource(String) and convert it to a fil...

{Windows}Getting Aligned Blocks Of Memory
Hello, Could anyone point out what is the best way to get aligned blocks of memory. Posix provides posix_memalign, however is there a way to do this thing in Windows? TIA. -- Imanpreet Singh Arora "Minti" <imanpreet@gmail.com> wrote in message news:1167693892.322288.180270@s34g2000cwa.googlegroups.com... > Hello, > > Could anyone point out what is the best way to get aligned > blocks of memory. Posix provides posix_memalign, however is there a way > to do this thing in Windows? > _aligned_malloc and _aligned_free -- Roger Roger W...