【发布时间】:2018-01-05 18:29:45
【问题描述】:
目前是否可以编写函数,引用 const 限定对象,但没有 r 值?
// 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 或类似的。但我受制于外部约束。
感谢您的建议。
【问题讨论】:
-
也许可以解释那些“外部约束”?
-
删除的函数重载就够了吗?
-
它是 hpc 应用程序中序列化算法的一部分。输入可能非常大,并且由于性能下降而不需要不必要的副本。如果我把它转换成一个共享指针,我还有一个深拷贝。
-
“如果我把它转换成一个共享指针,我还有一个更深的副本” - 怎么样?
-
@Ron 这是个好主意。
标签: c++ function pass-by-reference