gpt4 book ai didi

c++ - 引用 const 对象但没有右值的函数

转载 作者:太空宇宙 更新时间:2023-11-03 10:39:42 26 4
gpt4 key购买 nike

目前是否可以编写函数,引用 const 合格对象,但没有右值?

// Takes no r-values
void foo(std::string& v) {
...
}
...
const string cstr("constant string");
foo("string"); // this does not compile, as wanted
foo(cstr); // this does not compile, as expected. But i would want it to
...

// Takes r-values, which is highly undesired
void foo2(const std::string& v) {
...
}
...
const string cstr("constant string");
foo("string"); // this does compile, but i want it to fail.
foo(cstr); // this does compile
...

问题的背景与稍后时间点的对象拷贝有关(foo 完成后)。基本上,引用被推送到队列并稍后处理。我知道,语义被搞乱了,需要一个 shared_ptr 或类似的东西。但我受制于外部约束。

感谢您的建议。

最佳答案

使用删除的函数重载:

void foo(std::string& v) {
std::cout << v;
}
void foo(const std::string& v) = delete;
void foo(const char* v) = delete;

或类似的。

关于c++ - 引用 const 对象但没有右值的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45394623/

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