Programing

C ++의 char * 대 std :: string

crosscheck 2020. 10. 10. 09:37
반응형

C ++의 char * 대 std :: string


C ++에서 s 배열을 관리하기 위해 std::string언제 사용해야 하며 언제 사용해야 합니까?char*char

char*성능 (속도)이 중요하고 메모리 관리로 인해 위험한 비즈니스를 기꺼이 받아들이려는 경우 사용해야하는 것 같습니다 .

고려해야 할 다른 시나리오가 있습니까?


복사를 피하기 위해 큰 경우 참조로 std :: strings 또는 인스턴스에 대한 포인터를 전달할 수 있으므로 char 포인터를 사용하여 실제 이점을 보지 못합니다.

실제 텍스트 인 모든 것에 std :: string / wstring을 사용합니다. char *하지만 다른 유형의 데이터에 유용하며 원하는대로 할당이 해제 될 수 있습니다. 그렇지 않으면 std :: vector가 갈 길입니다.

이 모든 것에는 예외가있을 수 있습니다.


내 관점은 :

  • "C"코드를 호출하지 않으면 char *를 사용하지 마십시오.
  • 항상 std :: string 사용 : 더 쉽고, 더 친숙하며, 최적화되고, 표준이며, 버그가 발생하지 않도록 방지하고, 확인되고 작동하는 것으로 입증되었습니다.

원시 문자열 사용

예, 때로는 정말 할 수 있습니다. const char *, 스택에 할당 된 char 배열 및 문자열 리터럴을 사용할 때 메모리 할당이 전혀없는 방식으로 수행 할 수 있습니다.

이러한 코드를 작성하려면 문자열이나 벡터를 사용하는 것보다 더 많은 생각과주의가 필요하지만 적절한 기술을 사용하면 수행 할 수 있습니다. 적절한 기술을 사용하면 코드가 안전 할 수 있지만 char []로 복사 할 때 복사되는 문자열의 길이에 대한 보증이 있는지 항상 확인하거나 크기가 큰 문자열을 정상적으로 확인하고 처리해야합니다. 그렇게하지 않으면 strcpy 기능 군이 안전하지 않다는 평판을 얻었습니다.

템플릿이 안전한 문자 버퍼 작성을 돕는 방법

char [] 버퍼의 안전성과 관련하여 템플릿은 버퍼 크기를 처리하기위한 캡슐화를 생성 할 수 있으므로 도움이 될 수 있습니다. 이와 같은 템플릿은 Microsoft에서 strcpy를 안전하게 대체하기 위해 구현합니다. 여기 예제는 내 코드에서 추출되었으며 실제 코드에는 더 많은 메서드가 있지만 기본 아이디어를 전달하기에 충분해야합니다.

template <int Size>
class BString
{
  char _data[Size];

  public:
  BString()
  {
    _data[0]=0;
    // note: last character will always stay zero
    // if not, overflow occurred
    // all constructors should contain last element initialization
    // so that it can be verified during destruction
    _data[Size-1]=0;
  }
  const BString &operator = (const char *src)
  {
    strncpy(_data,src,Size-1);
    return *this;
  }

  operator const char *() const {return _data;}
};

//! overloads that make conversion of C code easier 
template <int Size>
inline const BString<Size> & strcpy(BString<Size> &dst, const char *src)
{
  return dst = src;
}

당신이 사용해야 하나의 기회 char*가 아니라는 std::string정적 문자열 상수를 필요로 할 때입니다. 그 이유는 모듈이 정적 변수를 초기화하는 순서를 제어 할 수없고 다른 모듈의 다른 전역 개체가 초기화되기 전에 문자열을 참조 할 수 있기 때문입니다. http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Static_and_Global_Variables

std::string 장점 :

  • 메모리를 관리합니다 (문자열이 커질 수 있으며 구현시 더 큰 버퍼를 할당합니다)
  • 상위 수준의 프로그래밍 인터페이스는 나머지 STL과 잘 작동합니다.

std::string cons: - two distinct STL string instances can not share the same underlying buffer. So if you pass by value you always get a new copy. - there is some performance penalty, but I'd say unless your requirements are special it's negligible.


You should consider to use char* in the following cases:

  • This array will be passed in parameter.
  • You know in advance the maximum size of your array (you know it OR you impose it).
  • You will not do any transformation on this array.

Actually, in C++, char* are often use for fixed small word, as options, file name, etc...


When to use a c++ std::string:

  • strings, overall, are more secure than char*, Normally when you are doing things with char* you have to check things to make sure things are right, in the string class all this is done for you.
  • Usually when using char*, you will have to free the memory you allocated, you don't have to do that with string since it will free its internal buffer when destructed.
  • Strings work well with c++ stringstream, formatted IO is very easy.

When to use char*

  • Using char* gives you more control over what is happening "behind" the scenes, which means you can tune the performance if you need to.

Use (const) char* as parameters if you are writing a library. std::string implementations differ between different compilers.


If you want to use C libraries, you'll have to deal with C-strings. Same applies if you want to expose your API to C.


You can expect most operations on a std::string (such as e.g. find) to be as optimized as possible, so they're likely to perform at least as well as a pure C counterpart.

It's also worth noting that std::string iterators quite often map to pointers into the underlying char array. So any algorithm you devise on top of iterators is essentially identical to the same algorithm on top of char * in terms of performance.

Things to watch out for are e.g. operator[] - most STL implementations do not perform bounds checking, and should translate this to the same operation on the underlying character array. AFAIK STLPort can optionally perform bounds checking, at which point this operator would be a little bit slower.

So what does using std::string gain you? It absolves you from manual memory management; resizing the array becomes easier, and you generally have to think less about freeing memory.

If you're worried about performance when resizing a string, there's a reserve function that you may find useful.


if you are using the array of chars in like text etc. use std::string more flexible and easier to use. If you use it for something else like data storage? use arrays (prefer vectors)


Even when performance is crucial you better use vector<char> - it allows memory allocation in advance (reserve() method) and will help you avoid memory leaks. Using vector::operator[] leads to an overhead, but you can always extract the address of the buffer and index it exactly like if it was a char*.


AFAIK internally most std::string implement copy on write, reference counted semantics to avoid overhead, even if strings are not passed by reference.

참고URL : https://stackoverflow.com/questions/801209/char-vs-stdstring-in-c

반응형