Prabhu
Prabhu

Reputation: 3528

Constructor with reference arguments in g++ compiler

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

Upvotes: 0

Views: 240

Answers (3)

anon
anon

Reputation:

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.

Upvotes: 12

graham.reeds
graham.reeds

Reputation: 16476

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

Upvotes: 1

James Curran
James Curran

Reputation: 103485

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.

Upvotes: 2

Related Questions