Advertisement Jump to content

Archived

This topic is now archived and is closed to further replies.

BlitzKrieg

Deleting objects within member functions

This topic is 6081 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

Is delete''ing an object within it''s own member function legal? MSVC++ doesn''t complain at compile, and i don''t get any errors when running a small test program, but i''m wondering if this is actually an ok practice, will it be portable between compilers, or is it running ok simply because memory isn''t being overwritten before the member function returns. eg:
  
class Test
{
public:
	Test()
	{
		myVar = 0;
	}

	~Test()
	{}

	void Kill()
	{
		myVar = 1;
		delete this;
	}

	int myVar;
};

int main()
{
	Test* myTest = new Test;

	if ( myTest != 0 )
	{
		myTest->Kill();
	}

	return 0;
}

  
I removed some of the test output code. Thanks.

Share this post


Link to post
Share on other sites
Advertisement
quote:
Original post by BlitzKrieg
Is delete''ing an object within it''s own member function legal?

Yes, but it''s semantically dubious. It is often better to manage object lifetime via some handle class, such as the smart pointers on offer at Boost''s website. If you familiarise yourself with the alternatives, then the times that an object needs to delete itself should become self-evident (i.e. the times when an alternative will not do).

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

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

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!