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....
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.
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.
I think if you make the constructor accept a const std::string&
then the CxUser(string("xxx-xxx-x-xxxx"))
should work.
精彩评论