user1287944
user1287944

Reputation:

usage of reference

void fn(string &s)
{
    //....
}

//use the function    
fn("helloworld");

Firstly, it's wrong to initiate a non-const string with a const char string.

After I add const in the parameter, it compiles.

But is it right to reference a temporary object string("helloworld") on stack?

Is it sure that string("helloworld") gets called?

--

edits.

If a temporary string is created, how the compiler judges that the object string("helloworld") is const from the constructor of std::string(const char*)?

Upvotes: 0

Views: 175

Answers (3)

James Kanze
James Kanze

Reputation: 153899

But is it right to reference a temporary object string("helloworld") on stack?

In this case, probably, but you do have to pay attention to the lifetime of the object. The temporary will cease to exist at the end of the full expression; if fn saves a pointer or a reference to it, you're in trouble. This is typically not a problem with a free function, like your fn (but it can be); it could be a problem if the temporary were an argument to a constructor in a new expression (but the author of the class should document any lifetime requirements which go beyond the constructor invocation).

Upvotes: 3

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

But is it right to reference a temporary object string("helloworld") on stack?

Yes, why not?

Is it sure that string("helloworld") gets called?

Yes, as long string provides an implicit constructor using a const char* argument this is garuanteed (std::string does so).

Upvotes: 2

Luchian Grigore
Luchian Grigore

Reputation: 258548

But is it right to reference a temporary object string("helloworld") on stack?

Yes, as long as the reference is const, the lifetime of the temporary will be extended.

Is it sure that string("helloworld") gets called?

Yes, a temporary is created using the conversion constructor std::string(const char*). Note however that the compiler can optimize this step out.

Upvotes: 5

Related Questions