我应该使用unique_ptr作为字符串吗?

Aki*_*ido 1 c++

我是C++的新手.

我认为使用unique_ptr/ shared_ptr是处理指针的"方法",但是我应该使用unique_ptrs代表std::strings吗?

Gam*_*a.X 5

你为什么想这么做?

std :: string对象自行管理"包含"字符串(内存字节)的生命周期.

因为你是C++的新手.在你的函数/类方法中,我会建议你在堆栈上创建你的对象:像这样:

  std::string s;
Run Code Online (Sandbox Code Playgroud)

而不是使用堆:

 std::string* s = new std::string();
Run Code Online (Sandbox Code Playgroud)

当对象超出范围时,将在销毁时创建对象.所以不需要智能指针.

您可以点击此链接了解更多信息:http://www.learncpp.com/cpp-tutorial/79-the-stack-and-the-heap/