I have a method like this:
std::unique_ptr<const Stats> Table::GetStats() const {
std::unique_ptr<Stats> result;
// ...
// Prepare stats. Under some conditions an exception may be thrown.
// ...
return result;
}
问题在于它无法编译:
我可以通过以下方法绕过使其编译:错误:无法将“std::unique_ptr”左值绑定到“std::unique_ptr&&”
return std::unique_ptr<const Stats>(result.release());
但这似乎有点过度了。我不明白,在C ++的角度看,第一段代码有什么问题吗?是否有更优雅的解决方案?
// 准备统计数据。某些情况下可能会抛出异常。
- Alexey Usachovreturn { std::move(result) };
。 - Richard Hodges