tags:

views:

91

answers:

3

Hi All,

Have a look at the following piece of code

Header File:

class CxUser
{ 
public:
    CxUser(string& guid) {} 
};

I have a c++ file that instantiates the class using CxUser(string("xxx-xxx-x-xxxx")). But this statement fails to compile in g++ with error "no matching function for call to CxUser::CxUser(std::string)" whereas it compiles in VC++. Surprisingly, the following piece of code to instantiate the class works.

string guid("xxx-x-xxxx-xxx-xx"); CxUser user(guid);

Any help would be appreciated....

+12  A: 

You need:

class CxUser{ public: CxUser(const string& guid) {} }

When you say:

CxUser c( "foobar" );   // or whatever

a temporary string object is created from the characterv array. In C++ you cannot bind non-const references to temporaries.

anon
+2  A: 

You are asking to pass a reference to a string -- essentially a pointer to the location where it is stored. But when you create the anonymous temporary like that, it isn't stored anywhere --- "there's no there there" -- there's nothing to pass. By storing it in a named temporary, you give it a location to work with.

When you use a non-const reference as a parameter, you imply that you are going to change the reference, which is non-existant, so you can't change it. When you use a const reference, the compiler know you can't change it, so it can do some magic so that the anonymous temporary reference parameter works.

James Curran
If this were the case, you couldn't call non-const members on a temporary (which receive a pointer to non-const `this`), but you can.
Ben Voigt
@Ben: not legally, no.
Konrad Rudolph
@Konrad: Are you saying that you can't legally call non-const members on a temporary?
Ben Voigt
+1  A: 

I think if you make the constructor accept a const std::string& then the CxUser(string("xxx-xxx-x-xxxx")) should work.

graham.reeds
UncleZeiv
Well yes. Anytime you pass a non-POD value you should pass it by either reference or pointer.
graham.reeds