Jump to content
  • Advertisement
Sign in to follow this  
load_bitmap_file

making auto_ptr explode

This topic is 4721 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I realized today that you can do this:
#include <memory>

int main()
{
	int n = 5;
	int* ptr = &n;
	std::auto_ptr<int*> aPtr(&ptr);
}
For those who don't feel like thinking, this makes delete get called on the ptr that was not allocated with new in auto_ptr's deconstructor, which causes bad things to happen (undefined behavior). So, is this allowed because there's no way to tell if a pointer was allocated with new or not? I am a bit curious that auto_ptr can be exploded so easily in this way.

Share this post


Link to post
Share on other sites
Advertisement
If you write code like that, you deserve the explosion that comes with it.

Plus there is no platform independent way to tell where a pointer comes from (if it was allocated via new or not).

Share this post


Link to post
Share on other sites
Quote:
Original post by Washu
If you write code like that, you deserve the explosion that comes with it.

Quote:
Original post by mhamlin
Besides, why would you ever want to attach an auto_ptr to a variable on the stack?


I don't intend to write code like this. I was wondering if it would be "allowed" [grin].

Quote:
Original post by Washu
Plus there is no platform independent way to tell where a pointer comes from (if it was allocated via new or not).


Okay, so that's the explanation. Thanks. [smile]

Share this post


Link to post
Share on other sites
std::auto_ptr is probably the least safe part of the std library.

boost::scoped_ptr tries to provide a safe implementation (you'll get a compile time errror if you try to use it in a std::container) but you can still explicitly constuct one from a pointer to memory on the stack.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!