Hello world bug with references and initializer lists

Below is some code I expected to print "Hello world" twice. In fact, it prints "Hello world" once and then throws an Access Exception.

The code to print both of the messages are near-identical:
#include <iostream>
#include <vector>

using namespace::std;

class VectorWrap1 {
public:
	vector<string>& v;
	
	// *** Reference parameter ***
	VectorWrap1(vector<string>& v_) : v(v_) {} 
};

class VectorWrap2 {
public:
	vector<string>& v;
	
	// *** Non-reference parameter ***
	VectorWrap2(vector<string> v_) : v(v_) {} 
};

int main(){
	vector<string> v = { "Hello world" };

	VectorWrap1 w1(v);

	// ***** Prints "Hello world" *********
	cout << w1.v[0].c_str() << endl;

	VectorWrap2 w2(v);

	// ***** Throws access exception *****
	cout << w2.v[0].c_str() << endl;

	return 0;
}

It seems as if VectorWrap2's reference member is being initialized by the constructor's non-reference parameter without any conversion taking place.

Shouldn't this generate a compile-time error?

Comments

  • Okay, so this was an interesting one to debug. The issue you're having happens because of either line.16 or line 19.

    The reason you're not getting the right output is because of what your compiler is expecting.
    vector<string>& v; <-- this is expecting a reference value ot be passed to it such as in VectorWrap1
    VectorWrap2(vector<string> v_) : v(v_) {} <-- this is attempting to pass a non-reference value to something expecting a reference value. 
    
    my Visual C++ compiler will not run this code and gives me errors while me GCC compiler will however outputs weird characters (probably originating from a random memory address that's being passed to vector<string>& v; by v_.

    To fix it, and get a proper output, you should remove the '&' from vector<string>&v;
  • Raikiriu wrote:
    Okay, so this was an interesting one to debug. The issue you're having happens because of either line.16 or line 19.

    The reason you're not getting the right output is because of what your compiler is expecting.
    vector<string>& v; <-- this is expecting a reference value ot be passed to it such as in VectorWrap1
    VectorWrap2(vector<string> v_) : v(v_) {} <-- this is attempting to pass a non-reference value to something expecting a reference value. 
    
    my Visual C++ compiler will not run this code and gives me errors while me GCC compiler will however outputs weird characters (probably originating from a random memory address that's being passed to vector<string>& v; by v_.

    To fix it, and get a proper output, you should remove the '&' from vector<string>&v;
    To expand on this,
    http://en.wikipedia.org/wiki/Reference_%28C%2B%2B%29

    References must be assigned a value at declaration. GCC is apparently pretty loose with the standard in this case.
Sign In or Register to comment.