【问题标题】:Function that takes a reference of a const object but no r-value引用 const 对象但没有 r 值的函数
【发布时间】: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


【解决方案1】:

使用已删除的函数重载:

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

或类似的。

【讨论】:

  • 非常好的解决方案。
【解决方案2】:

您可以明确允许 const 引用,同时禁止 r-value refs:

void foo(const std::string& v) {
}

void foo(std::string& v) {
}

void foo(std::string&& v) = delete;

【讨论】:

  • 非常感谢。 @Ron 提出了类似的方法。
猜你喜欢
  • 2013-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多