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

Recommended Answers

All 3 Replies

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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.