Create and Delete

Let's start things off by learning how to create and destroy strings.

C++ offers many methods to create strings from C or C++ strings. Under the hood, there is always a C string involved for creating a C++ string. That changes with C++14, because the new C++ standard support C++ string literals: std::string str{"string"s}. The C string literals "string literal" becomes with the suffix s a C++ string literal: "string literal"s.

The table gives you an overview of the methods to create and delete a C++string.

Methods Example
Default std::string str
Copies from a C++ string std::string str(oth)
Moves from a C++ string std::string str(std::move(oth))
From the range of a C++ string std::string(oth.begin(), oth.end())
From a substring of a C++ string std::string(oth, otherIndex)
From a substring of a C++ string std::string(oth, otherIndex, strlen)
From a C string std::string str("c-string")
From a C array std::string str("c-array", len)
From characters std::string str(num, 'c')
From a initializer list std::string str({'a', 'b', 'c', 'd'})
From a substring str= other.substring(3, 10)
Destructor str.~string()

Methods to create and delete a string

Get hands-on with 1400+ tech skills courses.