Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::string vs. char*

Tags:

c++

does std::string store data differently than a char* on either stack or heap or is it just derived from char* into a class?

like image 354
Elofin Avatar asked Apr 20 '10 03:04

Elofin


People also ask

Is char * the same as string?

char is a primitive data type whereas String is a class in java. char represents a single character whereas String can have zero or more characters.

What is the difference between char * and string in C++?

Think of (char *) as string. begin(). The essential difference is that (char *) is an iterator and std::string is a container.

What is the difference between const char * and string?

string is an object meant to hold textual data (a string), and char* is a pointer to a block of memory that is meant to hold textual data (a string). A string "knows" its length, but a char* is just a pointer (to an array of characters) -- it has no length information.

Why is a char * a string?

char *A is a character pointer. it's another way of initializing an array of characters, which is what a string is. char A, on the other hand, is a single char. it can't be more than one char.


1 Answers

char*

  • Is the size of one pointer for your CPU architecture.
  • May be a value returned from malloc or calloc or new or new[].
    • If so, must be passed to free or delete or delete[] when you're done.
    • If so, the characters are stored on the heap.
  • May result from "decomposition" of a char[ N ] (constant N) array or string literal.
    • Generically, no way to tell if a char* argument points to stack, heap, or global space.
  • Is not a class type. It participates in expressions but has no member functions.
  • Nevertheless implements the RandomAccessIterator interface for use with <algorithm> and such.

std::string

  • Is the size of several pointers, often three.
  • Constructs itself when created: no need for new or delete.
    • Owns a copy of the string, if the string may be altered.
    • Can copy this string from a char*.
    • By default, internally uses new[] much as you would to obtain a char*.
  • Provides for implicit conversion which makes transparent the construction from a char* or literal.
  • Is a class type. Defines other operators for expressions such as catenation.
    • Defines c_str() which returns a char* for temporary use.
  • Implements std::string::iterator type with begin() and end().
    • string::iterator is flexible: an implementation may make it a range-checked super-safe debugging helper or simply a super-efficient char* at the flip of a switch.
like image 60
Potatoswatter Avatar answered Sep 26 '22 01:09

Potatoswatter