954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

References to objects and destructors

Am I correct assuming that a reference to an object will not call the object's destructor when the reference goes out of scope? The code I attached supports my assumption but I'm not certain if its correct...Any comments?

#include <iostream>

class myint
{
	public:

		myint():itsvalue(0) {}
		myint(unsigned long val):itsvalue(val) { std::cout << "constructing->" << itsvalue << std::endl; }

		~myint() { std::cout << "destroying->" << itsvalue << std::endl; }

		std::ostream& print(std::ostream & out) const { return out << itsvalue; }

	private:

		unsigned long itsvalue;
	
};

std::ostream& operator <<(std::ostream & out, const myint & m)
{
	return m.print(out);
}

myint& myfunc(void)
{
	myint *ans = new myint(123);
	return *ans;
}

void myfunc2(void)
{
	myint & myr = myfunc();

	std::cout << myr << std::endl;
	//the reference myr doesn't call the destructor ~myint() when it goes out of scope
}

int main()
{
	myfunc2();
	return 0;
}
gerard4143
Nearly a Posting Maven
2,272 posts since Jan 2008
Reputation Points: 512
Solved Threads: 387
 

You are correct. A reference is not actually an instance of a class. A reference is more like a pointer, but doesn't have all the extra syntax. Thus, the reference can reach the end of its life, or go out of scope, without destroying the original object because the original object may not have reached the end of its life yet.

Fbody
Posting Maven
2,930 posts since Oct 2009
Reputation Points: 833
Solved Threads: 393
 

As Fbody made clear, that object will only die when you hit it with delete, and the reference IS the object - not a copy of it, not a pointer to it.

If you replace myfunc with the following, you'll see that the object dies as soon as it goes out of scope.

myint& myfunc(void)
{
	myint ans = myint(123);
	return ans;
}
Moschops
Practically a Master Poster
620 posts since Sep 2008
Reputation Points: 258
Solved Threads: 117
 
You are correct. A reference is not actually an instance of a class. A reference is more like a pointer, but doesn't have all the extra syntax. Thus, the reference can reach the end of its life, or go out of scope, without destroying the original object because the original object may not have reached the end of its life yet.

Thanks for the reply...One minute after I posted I thought of this situation

int main()
{
	myint me(123);
	myint &you = me;

	return 0;
}


which shows that the reference to an object mustn't call the destructor..I think I need some sleep.

gerard4143
Nearly a Posting Maven
2,272 posts since Jan 2008
Reputation Points: 512
Solved Threads: 387
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You