gpt4 book ai didi

c++ - const 引用函数参数 : Is it possible to disallow temporary objects?

转载 作者:太空狗 更新时间:2023-10-29 19:51:16 26 4
gpt4 key购买 nike

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

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

例子:

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

接口(interface)告诉客户端参数不会被改变,如果参数已经是 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;

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

关于c++ - const 引用函数参数 : Is it possible to disallow temporary objects?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50211811/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com