Sign in to follow this  
RedKMan

Returning by constant reference

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this