Jump to content
  • Advertisement
Sign in to follow this  
RedKMan

Returning by constant reference

This topic is 3192 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'm getting a warning from the code below:- warning C4172: returning address of local variable or temporary
#include <vector>
#include <iostream>
#include <math.h>
#include <string>


std::vector<int> int_vector; // vector of ints

const unsigned& getValueAt(unsigned index);

int main()
{
	for(int index = 1; index <= 10; index++)
	{
		int_vector.push_back(index);
	}

	for(unsigned index1 = 0; index1 < int_vector.size(); index1++)
	{
		std::cout << int_vector[index1] << "    ";
	}

	std::cout << std::endl << std::endl;

	std::cout << "The value stored at position 5 is, " << getValueAt(5) << ".";

	std::cout << std::endl << std::endl;

}


const unsigned& getValueAt(unsigned index)
{
	return int_vector[index - 1];
}

I'm trying to make my code as clean as possible, is what I'm doing naughty? If so, is there a cleaner solution? This code is just a model for a similiar issue I'm having in a larger project.

Share this post


Link to post
Share on other sites
Advertisement
Your vector is "int". You return "unsigned". It does an implicit conversion and that resulting converted variable is a temp... which you return an address of (or a reference to). This is really bad and I have a header file with a pragma that converts any warning 4172 to an error!

And like ripoff said, if in your "real" code you're also using a primitive type... best to just return by value.

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.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!