因为这就是条件运算符的工作方式。
您正在调用?:
两个操作数,其中一个是 type 的左值,std::string const
另一个是 type 的左值char const[1]
。条件运算符的语言规则......真的很复杂。相关规则是:
Otherwise, if the second and third operand have different types and either has (possibly cv-qualified) class type, or if both are glvalues of the same value category and the same type except for cv-qualification, an attempt is made to form an implicit conversion sequence from each of those operands to the type of the other. [ <em>Note: Properties such as access, whether an operand is a bit-field, or whether a conversion function is deleted are ignored for that determination. — end note ] Attempts are made to form an implicit conversion sequence from an operand expression E1
of type T1
to a target type related to the type T2
of the operand expression E2
as follows:
Using this process, it is determined whether an implicit conversion sequence can be formed from the second operand to the target type determined for the third operand, and vice versa. If both sequences can be formed, or one can be formed but it is the ambiguous conversion sequence, the program is ill-formed. If no conversion sequence can be formed, the operands are left unchanged and further checking is performed as described below. Otherwise, if exactly one conversion sequence can be formed, that conversion is applied to the chosen operand and the converted operand is used in place of the original operand for the remainder of this subclause. [ <em>Note: The conversion might be ill-formed even if an implicit conversion sequence could be formed. — <em>end note ]
Can't convert std::string const
to either char const(&)[1]
or char const*
, but you can convert char const[1]
to std::string const
(the inner nested bullet)... so that's what you get. A prvalue of type std::string const
. Which is to say, you're either copying one string or constructing a new one... either way, you're returning a string_view
to a temporary which goes out of scope immediately.
What you want is either what you had:
std::string_view myMethod(bool bla) {
return bla ? std::string_view(otherMethod()) : "";
}
or:
std::string_view myMethod(bool bla) {
return bla ? otherMethod() : ""sv;
}
The result of that conditional operator is a string_view
, with both conversions being safe.