简体   繁体   English

通过在函数调用中构造的引用传递对象

[英]Passing object by reference constructed in function call

we use some functions like this: 我们使用一些这样的功能:

std::string const & GetValue(std::string const & val) {
return val;
}

Is there a way to break compilation if a user is passing a temporary, because the code is sometimes misused using function calls like the following: 如果用户传递了临时文件,是否有一种方法可以中断编译,因为有时会使用如下函数调用来滥用代码:

std::string const & abc = GetValue(std::string("Value"));

And is there a difference (regarding the lifetime of the passed object) if the return value is not assigned to a reference, but to an object? 如果返回值未分配给引用,而是分配给对象,是否有区别(关于所传递对象的生存期)?

std::string def = GetValue(std::string("Value"));

Thanks a lot! 非常感谢!

You could add a deleted rvalue overload to prohibit binding to rvalues entirely: 您可以添加已删除的右值重载以完全禁止绑定右值:

void GetValue(std::string && val) = delete;

Alternatively, you could make the rvalue overload return a prvalue, thus avoiding dangling references: 或者,您可以使rvalue重载返回prvalue,从而避免悬挂引用:

std::string GetValue(std::string && val) { return GetValue(val); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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