c++ - 如何在 C++ 中将 const ref a 返回给局部变量?

标签 c++ boost

我有一个无法更改函数参数的函数。我需要返回对在此函数中创建的 std::string 的 const 引用。我尝试使用 boost shared_ptr,但这不起作用。为什么?我该如何进行这项工作?

const std::string& getVal(const std::string &key) {
  boost::shared_ptr<std::string> retVal(new std::string());
  ... //build retVal string with += operator based on key
  return *retVal;
}

最佳答案

您不能使用 C++ 从函数返回对局部变量的引用。尽管在 c++0x 中这是可能的。

在堆上分配字符串,稍后手动清理:

如果无法更改函数的接口(interface),则需要在堆上创建它,然后手动删除它。

//Remember to free the address that getVal returns
const std::string& getVal(const std::string &key) {
  std::string *retVal = new std::string();
  ... //build retVal string with += operator based on key
  return *retVal;
}

相同的解决方案,但不是手动:

由于上述如果忘记手动释放最终会导致内存泄漏。我建议将此调用包装到一个类中并使用 RAII。 IE。在构造函数中,调用 getVal 并设置此类的一个成员指向它。在您类(class)的析构函数中,您将删除它。

为什么您使用 shared_ptr 提供的代码不起作用:

shared_ptr 通过引用计数工作。由于您正在销毁唯一的 shared_ptr 对象(按范围),因此没有引用剩余并且内存将被释放。要让它工作,你必须返回一个 shared_ptr,但你说你不能这样做。

关于c++ - 如何在 C++ 中将 const ref a 返回给局部变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/636755/

相关文章:

二十一点程序中体系结构 x86_64 的 C++ undefined symbol

c++ - 内联函数和 __thiscall __cdecl Bjarne String 示例

c++ - 可以使用带有 boost 的 C++ 匿名函数吗?

c++ - boost 目录迭代器

c++ - 对常规文件进行 Epoll

c# - 如何解释此堆栈跟踪

c++ - lambda 函数的 setter ?

c++ - boost::asio::io_service::在多个线程中运行

c++ - 将 boost::shared_array<char> 转换为 boost::shared_array<const char>

c++ - boost 图形库 : access violation in reading from adjacency_list in parallel mode