const 引用函数参数:是否可以禁止临时对象?

const reference function parameter: Is it possible to disallow temporary objects?

可以有一个强制执行以下语义的函数参数:

参数不会被函数改变。 调用函数永远不会为参数创建副本或临时对象。

示例:

void f(const std::string & str);

接口告​​诉客户端参数不会被改变,如果参数已经是std::string类型,则不会创建副本。

但仍然可以将其称为

const char * hello = "hello";
f(hello);

它在函数 f 进入之前创建一个临时 std::string 对象,并在退出 f 后再次销毁它。

是否可以通过不同的函数声明或通过(假设地)更改 std::string 实现来禁止此操作。

我将从这里开始。

or by (hypothetically) altering std::string implementation

不要这样,怕鼻魔。说真的,不要。让标准库以标准方式运行。

Is it possible to disallow this, either with a different function declaration

再声明就是机票,其实。添加一个接受右值引用的重载,并将其定义为已删除:

void f(std::string && str) = delete;

过载解析会为临时选择它,删除定义会导致错误。现在只能使用左值调用您想要的函数。