Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between ::std::string and std::string?

Tags:

c++

what is the difference between ::std::string and std::string The former is global? But global for what?Is not namespace std global? Thanks for helping me.

like image 698
DickHunter Avatar asked Jan 06 '17 05:01

DickHunter


People also ask

What is an std::string?

std::string class in C++ C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character.

What is the difference between std::string and std::vector?

std::string has a huge number of string-related functions which make it easy to manipulate strings. 2. std::vector, on the other hand, is guaranteed to be contiguous in memory -- that is, &data[x + 1] = &data[x] + sizeof(data[x]). std::string has NO guarantee that it is contiguous in memory.

What are the 2 types of C++ strings?

There are two types of strings commonly used in C++ programming language: Strings that are objects of string class (The Standard C++ Library string class) C-strings (C-style Strings)

Why do I need std::string?

Because the declaration of class string is in the namespace std. Thus you either need to always access it via std::string (then you don't need to have using) or do it as you did. Save this answer.


1 Answers

::std::string means string in namespace std in the global namespace. The leading :: forces the lookup to start in the global namespace. Therefore ::std::string always means the string type from the C++ standard library.

std::string means string in namespace std, where std will be looked up in the current scope. Therefore, if there is a class, namespace, or enum named std, name lookup might find that std.

#include <string>
namespace foo {
  namespace std {
    class string { ... };
    namespace bar {
      std::string s;    // means foo::std::string
      ::std::string s;  // means string from standard library
    }
  }
}

It is not necessary to use the leading :: as long as you and your collaborators agree to not name anything std. It's just good style.

like image 154
Brian Bi Avatar answered Oct 21 '22 13:10

Brian Bi