简体   繁体   English

我应该对字符串使用 unique_ptr 吗?

[英]Should I use unique_ptr for a string?

I'm new to C++.我是 C++ 的新手。 I've heard that using unique_ptr / shared_ptr is the "way to go" for references to data allocated on the heap.我听说使用unique_ptr / shared_ptr是引用堆上分配的数据的“方法”。 Does it make sense, therefore, to use unique_ptr s instead of std::string s?因此,使用unique_ptr而不是std::string是否有意义?

Why would you want to do that?你为什么要这样做?

An std::string object manages the life time of the "contained" string (memory bytes) by itself. std::string 对象自己管理“包含”字符串(内存字节)的生命周期。

Since you are new to C++.因为你是 C++ 的新手。 Inside your function / class method, I will advice you create your objects on the stack: Like so:在你的函数/类方法中,我会建议你在堆栈上创建你的对象:像这样:

  std::string s;

as opposed to using the heap:与使用堆相反:

 std::string* s = new std::string();

Objects created on the stack will be destroyed when your object goes out of scope.当您的对象超出范围时,在堆栈上创建的对象将被销毁。 So there is no need for smart pointers.所以不需要智能指针。

You can following this link to know more:http://www.learncpp.com/cpp-tutorial/79-the-stack-and-the-heap/您可以通过此链接了解更多信息:http ://www.learncpp.com/cpp-tutorial/79-the-stack-and-the-heap/

There's no need to use a std::unique_ptr or std::shared_ptr for a std::string .没有必要为std::string使用std::unique_ptrstd::shared_ptr

You do not have to allocate memory for a simple std::string .您不必为简单的std::string分配内存。

std::string str = "abc";

As simple as that.就这么简单。 No need for memory allocation, as the std::string manages the 'real' string by itself.不需要内存分配,因为std::string管理“真实”字符串。


There are situations which may lead to usage of a pointer, though it is likely a class/struct instance.在某些情况下可能会导致使用指针,尽管它可能是一个类/结构实例。

For instance consider using例如考虑使用

std::unique_ptr<MyClass> p;

instead of而不是

MyClass *p;

if possible.如果可能的话。

You normally don't need pointers to strings, just like you generally don't need pointers to integers.您通常不需要指向字符串的指针,就像您通常不需要指向整数的指针一样。 You can just store string values, you can pass string values, etc.您可以只存储字符串值,也可以传递字符串值等。

But if you are in the exceptional situation where you'd need a pointer to a string, then yes, std::unique_ptr<std::string> or std::shared_ptr<std::string> are better than std::string* .但是,如果您处于需要指向字符串的指针的特殊情况,那么是的, std::unique_ptr<std::string>std::shared_ptr<std::string>std::string*更好std::string* .

An std::unique_ptr ensures that the object pointed is not accidentally copied and properly deleted. std::unique_ptr确保指向的对象不会被意外复制和正确删除。 As you should avoid dynamic allocation as much as you can, you can simply keep the std::string as a member of your class.由于您应该尽可能避免动态分配,因此您可以简单地将std::string保留为类的成员。 If it is a returned value, as already pointed out, the string class is smart enough to properly move resources in a safe way.如果它是一个返回值,正如已经指出的那样,字符串类足够聪明,可以以安全的方式正确移动资源。 You don't need to guarantee that a string is unique, I mean, no copies exist, so the unique ptr is just a too strong constraint.你不需要保证一个字符串是唯一的,我的意思是,不存在副本,所以唯一的 ptr 只是一个太强的约束。 KIS rule: Keep it simple. KIS 规则:保持简单。

Usually, and by default the answer is no, as others have suggested.通常,默认情况下,答案是否定的,正如其他人所建议的那样。 However - sometimes, the answer may paradoxically be "Possibly Yes"!然而 - 有时,答案可能矛盾的是“可能是”! How come?怎么来的?

  • With std::string , you don't control how, when and by whom your buffer is allocated.使用std::string ,您无法控制如何、何时以及由谁分配缓冲区。 While this is somewhat mitigated if you use a different allocator ( std::basic_string<char, MyAllocatorType> ) - the resulting class is not std::string ;如果您使用不同的分配器( std::basic_string<char, MyAllocatorType>std::basic_string<char, MyAllocatorType>这会有所缓解 - 结果类不是std::string and will generally not be accepted by functions which taken std::string 's.并且通常不会被采用std::string的函数接受。 And it may not make sense to get into allocators just for this purpose.仅仅为了这个目的而进入分配器可能没有意义。
  • More specifically, you can allow your unique-pointer-based string class to be created as an owning wrapper for an existing buffer.更具体地说,您可以允许将基于唯一指针的字符串类创建为现有缓冲区的拥有包装器。
  • Now that we can use string_view 's - and they are even in the standard in C++20 ( std::string_view ) - you don't have to rewrite the whole string class for unique-pointer-based strings;现在我们可以使用string_view的——它们甚至在 C++20 的标准中( std::string_view )——你不必为基于唯一指针的字符串重写整个字符串类; all you need is to create a string view over it, using the raw pointer and the size in bytes (or size - 1 if you want better null-termination safety.) And if you do want the std::string methods still, they'll be one-liners, eg您所需要的只是创建一个字符串视图,使用原始指针和以字节为单位的大小(如果您想要更好的空终止安全,则为 size - 1。)如果您仍然想要 std::string 方法,它们将是单行的,例如
    std::string_view view() const { return std::string_view{uptr_.get(), size_}; } substr(size_type pos = 0, size_type count = npos) const { return view().substr(pos, count); }
  • If you want to update a string in-place, while maintaining its size - an std::string won't work for you: Either its completely constant, or mutable both in size and in contents.如果您想就地更新字符串,同时保持其大小 - std::string对您不起作用:要么是完全不变的,要么在大小和内容上都是可变的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在这种情况下,应该使用unique_ptr还是shared_ptr? - Should I use unique_ptr or shared_ptr in this case? 我应该使用 shared_ptr 还是 unique_ptr - Should I use shared_ptr or unique_ptr 我应该使用 QScopedPointer 还是 std::unique_ptr? - Should I use QScopedPointer or std::unique_ptr? 我应该使用unique_ptr来保留班级成员吗? - Should I use unique_ptr to keep class' members? 我应该分配还是重置unique_ptr? - Should I assign or reset a unique_ptr? 使用 unique_ptr 并返回一个引用,或者我应该使用 shared_ptr 并在需要时制作副本 - Use a unique_ptr and return a reference or should I use a shared_ptr and make copies if needed C++:使用 string&amp; 和 unique_ptr<someclass> &amp; 用于 map <string, unique_ptr<someclass> &gt;</string,></someclass> - C++: use string& and unique_ptr<SomeClass>& for map<string, unique_ptr<SomeClass>> 如果我需要多态,我应该使用原始指针而不是unique_ptr吗? - If I need polymorphism should I use raw pointers instead of unique_ptr? 当我可以在析构函数中销毁对象时,为什么要使用std :: unique_ptr? - Why should I use an std::unique_ptr when I could just destroy the object in my destructor? 我应该使用std :: vector的std :: unique_ptr吗 <T[]> 如果内存稀疏并且我不会调整大小 - Should i use std::vector of std::unique_ptr<T[]> if memory is sparse and i'm not going to resize
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM