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;
}

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.

Edited 5 Years Ago by Fbody: n/a

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;
}

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.

Edited 5 Years Ago by gerard4143: n/a

This question has already been answered. Start a new discussion instead.