C++ String Assignment Core

std::string::operator=

Assigns a new value to the string, replacing its current contents.

(See member function assign for additional assignment options).

Parameters

str
A string object, whose value is either copied (1) or moved (5) if different from (if moved, str is left in an unspecified but valid state).
s
Pointer to a null-terminated sequence of characters.
The sequence is copied as the new value for the string.
c
A character.
The string value is set to a single copy of this character (the string length becomes ).
il
An initializer_list object.
These objects are automatically constructed from initializer list declarators.
The characters are copied, in the same order.

Return Value


Example



Output:

Complexity

Unspecified, but generally linear in the new string length (and constant for the move version).

Iterator validity

Any iterators, pointers and references related to this object may be invalidated.

Data races

The object is modified.
The move assignment (5) modifies .

Exception safety

For the move assignment (5), the function does not throw exceptions (no-throw guarantee).
In all other cases, there are no effects in case an exception is thrown (strong guarantee).

If the resulting string length would exceed the max_size, a length_error exception is thrown.
A bad_alloc exception is thrown if the function needs to allocate storage and fails.

See also

string::assign
Assign content to string (public member function)
string::operator+=
Append to string (public member function)
string::insert
Insert into string (public member function)
string::replace
Replace portion of string (public member function)
string::string
Construct string object (public member function)
string::compare
Compare strings (public member function)
string (1)string& operator= (const string& str);
c-string (2)string& operator= (const char* s);
character (3)string& operator= (char c);
string (1)string& operator= (const string& str);
c-string (2)string& operator= (const char* s);
character (3)string& operator= (char c);
initializer list (4)string& operator= (initializer_list<char> il);
move (5)string& operator= (string&& str) noexcept;

It’s been 13 years since the first iteration of the C++ language. Danny Kalev, a former member of the C++ standards committee, explains how the programming language has been improved and how it can help you write better code.
Bjarne Stroustrup, the creator of C++, said recently that C++11 “feels like a new language — the pieces just fit together better.” Indeed, core C++11 has changed significantly. It now supports lambda expressions, automatic type deduction of objects, uniform initialization syntax, delegating constructors, deleted and defaulted function declarations, , and most importantly, rvalue references — a feature that augurs a paradigm shift in how one conceives and handles objects. And that’s just a sample.

The C++11 Standard Library was also revamped with new algorithms, new container classes, atomic operations, type traits, regular expressions, new smart pointers, facility, and of course a multithreading library.

A complete list of the new core and library features of C++11 is available here.

After the approval of the C++ standard in 1998, two committee members prophesied that the next C++ standard would “certainly” include a built-in garbage collector (GC), and that it probably wouldn’t support multithreading because of the technical complexities involved in defining a portable threading model. Thirteen years later, the new C++ standard, C++11, is almost complete. Guess what? It lacks a GC but it does include a state-of–the-art threading library.

In this article I explain the biggest changes in the language, and why they are such a big deal. As you’ll see, threading libraries are not the only change. The new standard builds on the decades of expertise and makes C++ even more relevant. As Rogers Cadenhead points out, “That’s pretty amazing for something as old as disco, Pet Rocks, and Olympic swimmers with chest hair.”

First, let’s look at some of the prominent C++11 core-language features.

Lambda Expressions

A lambda expression lets you define functions locally, at the place of the call, thereby eliminating much of the tedium and security risks that function objects incur. A lambda expression has the form:

[capture](parameters)->return-type {body}

The construct inside a function call’s argument list indicates the beginning of a lambda expression. Let’s see a lambda example.

Suppose you want to count how many uppercase letters a string contains. Using to traverses a char array, the following lambda expression determines whether each letter is in uppercase. For every uppercase letter it finds, the lambda expression increments , a variable defined outside the lambda expression:

It’s as if you defined a function whose body is placed inside another function call. The ampersand in [&Uppercase] means that the lambda body gets a reference to Uppercase so it can modify it. Without the ampersand, Uppercase would be passed by value. C++11 lambdas include constructs for member functions as well.

Automatic Type Deduction and

In C++03, you must specify the type of an object when you declare it. Yet in many cases, an object’s declaration includes an initializer. C++11 takes advantage of this, letting you declare objects without specifying their types:

Automatic type deduction is chiefly useful when the type of the object is verbose or when it’s automatically generated (in templates). Consider:

Instead, you can declare the iterator like this:

The keyword isn’t new; it actually dates back the pre-ANSI C era. However, C++11 has changed its meaning; no longer designates an object with automatic storage type. Rather, it declares an object whose type is deducible from its initializer. The old meaning of was removed from C++11 to avoid confusion.

C++11 offers a similar mechanism for capturing the type of an object or an expression. The new operator takes an expression and “returns” its type:

Uniform Initialization Syntax

C++ has at least four different initialization notations, some of which overlap.

Parenthesized initialization looks like this:

You can also use the notation for the same purpose in certain cases:

For POD aggregates, you use braces:

Finally, constructors use member initializers:

This proliferation is a fertile source for confusion, not only among novices. Worse yet, in C++03 you can’t initialize POD array members and POD arrays allocated using . C++11 cleans up this mess with a uniform brace notation:

With respect to containers, you can say goodbye to a long list of calls. In C++11 you can initialize containers intuitively:

Similarly, C++11 supports in-class initialization of data members:

Deleted and Defaulted Functions

A function in the form:

is called a defaulted function. The part instructs the compiler to generate the default implementation for the function. Defaulted functions have two advantages: They are more efficient than manual implementations, and they rid the programmer from the chore of defining those functions manually.

The opposite of a defaulted function is a deleted function:

Deleted functions are useful for preventing object copying, among the rest. Recall that C++ automatically declares a copy constructor and an assignment operator for classes. To disable copying, declare these two special member functions :

nullptr

At last, C++ has a keyword that designates a null pointer constant. replaces the bug-prone macro and the literal 0 that have been used as null pointer substitutes for many years. is strongly-typed:

is applicable to all pointer categories, including function pointers and pointers to members:

Delegating Constructors

In C++11 a constructor may call another constructor of the same class:

Constructor #2, the delegating constructor, invokes the target constructor #1.

Rvalue References

Reference types in C++03 can only bind to lvalues. C++11 introduces a new category of reference types called rvalue references. Rvalue references can bind to rvalues, e.g. temporary objects and literals.

The primary reason for adding rvalue references is move semantics. Unlike traditional copying, moving means that a target object pilfers the resources of the source object, leaving the source in an “empty” state. In certain cases where making a copy of an object is both expensive and unnecessary, a move operation can be used instead. To appreciate the performance gains of move semantics, consider string swapping. A naive implementation would look like this:

This is expensive. Copying a string entails the allocation of raw memory and copying the characters from the source to the target. In contrast, moving strings merely swaps two data members, without allocating memory, copying char arrays and deleting memory:

If you’re implementing a class that supports moving, you can declare a move constructor and a move assignment operator like this:

The C++11 Standard Library uses move semantics extensively. Many algorithms and containers are now move-optimized.

C++11 Standard Library

C++ underwent a major facelift in 2003 in the form of the Library Technical Report 1 (TR1). TR1 included new container classes (, , , and ) and several new libraries for regular expressions, tuples, function object wrapper and more. With the approval of C++11, TR1 is officially incorporated into standard C++ standard, along with new libraries that have been added since TR1. Here are some of the C++11 Standard Library features:

Threading Library

Unquestionably, the most important addition to C++11 from a programmer’s perspective is concurrency. C++11 has a thread class that represents an execution thread, promises and futures, which are objects that are used for synchronization in a concurrent environment, the async() function template for launching concurrent tasks, and the thread_local storage type for declaring thread-unique data. For a quick tour of the C++11 threading library, read Anthony Williams’ Simpler Multithreading in C++0x.

New Smart Pointer Classes

C++98 defined only one smart pointer class, , which is now deprecated. C++11 includes new smart pointer classes: shared_ptr and the recently-added unique_ptr. Both are compatible with other Standard Library components, so you can safely store these smart pointers in standard containers and manipulate them with standard algorithms.

New C++ Algorithms

The C++11 Standard Library defines new algorithms that mimic the set theory operations , and . The following listing applies the predicate to the range and uses , and to examine the range’s properties:

A new category of algorithms is also available. Using , copying an array of 5 elements to another array is a cinch:

The algorithm creates a range of sequentially increasing values, as if by assigning an initial value to , then incrementing that value using prefix ++. In the following listing, assigns the consecutive values {10,11,12,13,14} to the array , and {‘a’, ‘b’, ‘c’} to the char array .

C++11 still lacks a few useful libraries such as an XML API, sockets, GUI, reflection — and yes, a proper automated garbage collector. However, it does offer plenty of new features that will make C++ more secure, efficient (yes, even more efficient than it has been thus far! See Google’s benchmark tests), and easier to learn and use.

If the changes in C++11 seem overwhelming, don’t be alarmed. Take the time to digest these changes gradually. At the end of this process you will probably agree with Stroustrup: C++11 does feel like a new language — a much better one.

See also:

 

0 comments

Leave a Reply

Your email address will not be published. Required fields are marked *