std::string and literals

Tony Bryant brd@paradise.net.nz
Fri Jul 19 05:23:00 GMT 2002


If I have the following:

void function(const std::string &x)
{
   cout << x;
}

int main()
{
   function("abcd");
}


then a temporary std::string will be constructed, internal memory will be 
allocated and the string "abcd" will be copied.

Which is obviously not the most efficient...

Q. Is there a way to specifically create a std::string instance that will 
just be a reference to the given literal? (with copy on write semantics 
of course).

e.g.

int main()
{
   function( std::string::literal("abcd"));   //hypothetical named constructor
}


or better yet, have the compiler figure this out automatically:

e.g.

namespace std
{
	class basic_string...
	{
		basic_string(readonly char *x)	// hypothetical "readonly" keyword
		{
			// just make a reference to x here
		}
	};
};

the hypothetical "readonly" is kind of like a more restrictive version of 
"const", basically meaning that no-one will ever modify it..



More information about the Libstdc++ mailing list