简体   繁体   中英

C++ understand reference in default parameter

I have a question about reference in default parameter in C++.

Exemple : SWindows(const std::string&, int, const std::string& flag = "UDP");

I don't understand why this code compile (IDE Visual studio 2012). For me, a reference it's an object alias. So We can't declared this line. It's supposed that the "flag" already exists.

So it's a compiler optimization or a misunderstanding ?

A const lvalue can bind to a temporary object. That's all. So, that code is legal and well formed.

The lifetime of that temporary object will be extended as long as flag exists. It doesn't need to say, you can not bind a temporary object to a non-const lvalue reference.

You can do that with const references. You can also use rvalues with const references like:

void SomeFunction(SomeObject const& s)
 { ... };

And then you can call

SomeFunction(SomeObject());

You can do this because by saying its a const reference, you are telling you won't be modifying the referenced variable. If it wasn't a const& you wouldn't be able to do that.

To understand the code

SWindows(const std::string&, int, const std::string& flag = "UDP");

you should split it into two parts.

SWindows(const std::string&, int, const std::string& flag );

SWindows( SomeString, SomeInt, "UDP" );

As "UDP" is not of type std::string then it implicitly is converted to an object of type std::string by calling the constructor that accepts a string literal as its first argument. So the last statement is equivalent to

SWindows( SomeString, SomeInt, std::string( "UDP" ) );

The result of expression std::string( "UDP ) is a temporary object that you may bind to a const reference. So the const reference is an alias of that temporary object,

You can imagine this such a way that inside the body of the function there is definition

const std::string &flag = std::string( "UDP" );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM