std::vector:: operator=

Replaces the contents of the container.

[ edit ] Parameters

[ edit ] return value, [ edit ] complexity, [ edit ] example.

The following code uses to assign one std:: vector to another:

[ edit ] See also

  • conditionally noexcept

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Move Constructors and Move Assignment Operators (C++)

  • 9 contributors

This topic describes how to write a move constructor and a move assignment operator for a C++ class. A move constructor enables the resources owned by an rvalue object to be moved into an lvalue without copying. For more information about move semantics, see Rvalue Reference Declarator: && .

This topic builds upon the following C++ class, MemoryBlock , which manages a memory buffer.

The following procedures describe how to write a move constructor and a move assignment operator for the example C++ class.

To create a move constructor for a C++ class

Define an empty constructor method that takes an rvalue reference to the class type as its parameter, as demonstrated in the following example:

In the move constructor, assign the class data members from the source object to the object that is being constructed:

Assign the data members of the source object to default values. This prevents the destructor from freeing resources (such as memory) multiple times:

To create a move assignment operator for a C++ class

Define an empty assignment operator that takes an rvalue reference to the class type as its parameter and returns a reference to the class type, as demonstrated in the following example:

In the move assignment operator, add a conditional statement that performs no operation if you try to assign the object to itself.

In the conditional statement, free any resources (such as memory) from the object that is being assigned to.

The following example frees the _data member from the object that is being assigned to:

Follow steps 2 and 3 in the first procedure to transfer the data members from the source object to the object that is being constructed:

Return a reference to the current object, as shown in the following example:

Example: Complete move constructor and assignment operator

The following example shows the complete move constructor and move assignment operator for the MemoryBlock class:

Example Use move semantics to improve performance

The following example shows how move semantics can improve the performance of your applications. The example adds two elements to a vector object and then inserts a new element between the two existing elements. The vector class uses move semantics to perform the insertion operation efficiently by moving the elements of the vector instead of copying them.

This example produces the following output:

Before Visual Studio 2010, this example produced the following output:

The version of this example that uses move semantics is more efficient than the version that does not use move semantics because it performs fewer copy, memory allocation, and memory deallocation operations.

Robust Programming

To prevent resource leaks, always free resources (such as memory, file handles, and sockets) in the move assignment operator.

To prevent the unrecoverable destruction of resources, properly handle self-assignment in the move assignment operator.

If you provide both a move constructor and a move assignment operator for your class, you can eliminate redundant code by writing the move constructor to call the move assignment operator. The following example shows a revised version of the move constructor that calls the move assignment operator:

The std::move function converts the lvalue other to an rvalue.

Rvalue Reference Declarator: && std::move

Submit and view feedback for

Additional resources

  • <cassert> (assert.h)
  • <cctype> (ctype.h)
  • <cerrno> (errno.h)
  • C++11 <cfenv> (fenv.h)
  • <cfloat> (float.h)
  • C++11 <cinttypes> (inttypes.h)
  • <ciso646> (iso646.h)
  • <climits> (limits.h)
  • <clocale> (locale.h)
  • <cmath> (math.h)
  • <csetjmp> (setjmp.h)
  • <csignal> (signal.h)
  • <cstdarg> (stdarg.h)
  • C++11 <cstdbool> (stdbool.h)
  • <cstddef> (stddef.h)
  • C++11 <cstdint> (stdint.h)
  • <cstdio> (stdio.h)
  • <cstdlib> (stdlib.h)
  • <cstring> (string.h)
  • C++11 <ctgmath> (tgmath.h)
  • <ctime> (time.h)
  • C++11 <cuchar> (uchar.h)
  • <cwchar> (wchar.h)
  • <cwctype> (wctype.h)

Containers:

  • C++11 <array>
  • <deque>
  • C++11 <forward_list>
  • <list>
  • <map>
  • <queue>
  • <set>
  • <stack>
  • C++11 <unordered_map>
  • C++11 <unordered_set>
  • <vector>

Input/Output:

  • <fstream>
  • <iomanip>
  • <ios>
  • <iosfwd>
  • <iostream>
  • <istream>
  • <ostream>
  • <sstream>
  • <streambuf>

Multi-threading:

  • C++11 <atomic>
  • C++11 <condition_variable>
  • C++11 <future>
  • C++11 <mutex>
  • C++11 <thread>
  • <algorithm>
  • <bitset>
  • C++11 <chrono>
  • C++11 <codecvt>
  • <complex>
  • <exception>
  • <functional>
  • C++11 <initializer_list>
  • <iterator>
  • <limits>
  • <locale>
  • <memory>
  • <new>
  • <numeric>
  • C++11 <random>
  • C++11 <ratio>
  • C++11 <regex>
  • <stdexcept>
  • <string>
  • C++11 <system_error>
  • C++11 <tuple>
  • C++11 <type_traits>
  • C++11 <typeindex>
  • <typeinfo>
  • <utility>
  • <valarray>
  • vector<bool>
  • vector::~vector
  • vector::vector

member functions

  • vector::assign
  • vector::back
  • vector::begin
  • vector::capacity
  • C++11 vector::cbegin
  • C++11 vector::cend
  • vector::clear
  • C++11 vector::crbegin
  • C++11 vector::crend
  • C++11 vector::data
  • C++11 vector::emplace
  • C++11 vector::emplace_back
  • vector::empty
  • vector::end
  • vector::erase
  • vector::front
  • vector::get_allocator
  • vector::insert
  • vector::max_size
  • vector::operator[]
  • vector::operator=
  • vector::pop_back
  • vector::push_back
  • vector::rbegin
  • vector::rend
  • vector::reserve
  • vector::resize
  • C++11 vector::shrink_to_fit
  • vector::size
  • vector::swap

non-member overloads

  • relational operators (vector)
  • swap (vector)

std:: vector ::operator[]

Return value, iterator validity, exception safety.

CProgramming Tutorial

  • C Programming Tutorial
  • C - Overview
  • C - Features
  • C - History
  • C - Environment Setup
  • C - Program Structure
  • C - Hello World
  • C - Compilation Process
  • C - Comments
  • C - Keywords
  • C - Identifiers
  • C - User Input
  • C - Basic Syntax
  • C - Data Types
  • C - Variables
  • C - Integer Promotions
  • C - Type Conversion
  • C - Constants
  • C - Literals
  • C - Escape sequences
  • C - Format Specifiers
  • C - Storage Classes
  • C - Operators
  • C - Decision Making
  • C - While loop
  • C - Functions
  • C - Scope Rules
  • C - Pointers
  • C - Strings
  • C - Structures
  • C - Bit Fields
  • C - Typedef
  • C - Input & Output
  • C - File I/O
  • C - Preprocessors
  • C - Header Files
  • C - Type Casting
  • C - Error Handling
  • C - Recursion
  • C - Variable Arguments
  • C - Memory Management
  • C - Command Line Arguments
  • C Programming Resources
  • C - Questions & Answers
  • C - Quick Guide
  • C - Useful Resources
  • C - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Assignment Operators in C

In C, the assignment operator stores a certain value in an already declared variable. A variable in C can be assigned the value in the form of a literal, another variable or an expression. The value to be assigned forms the right hand operand, whereas the variable to be assigned should be the operand to the left of = symbol, which is defined as a simple assignment operator in C. In addition, C has several augmented assignment operators.

The following table lists the assignment operators supported by the C language −

Simple assignment operator (=)

The = operator is the most frequently used operator in C. As per ANSI C standard, all the variables must be declared in the beginning. Variable declaration after the first processing statement is not allowed. You can declare a variable to be assigned a value later in the code, or you can initialize it at the time of declaration.

You can use a literal, another variable or an expression in the assignment statement.

Once a variable of a certain type is declared, it cannot be assigned a value of any other type. In such a case the C compiler reports a type mismatch error.

In C, the expressions that refer to a memory location are called "lvalue" expressions. A lvalue may appear as either the left-hand or right-hand side of an assignment.

On the other hand, the term rvalue refers to a data value that is stored at some address in memory. A rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right-hand side but not on the left-hand side of an assignment.

Variables are lvalues and so they may appear on the left-hand side of an assignment. Numeric literals are rvalues and so they may not be assigned and cannot appear on the left-hand side. Take a look at the following valid and invalid statements −

Augmented assignment operators

In addition to the = operator, C allows you to combine arithmetic and bitwise operators with the = symbol to form augmented or compound assignment operator. The augmented operators offer a convenient shortcut for combining arithmetic or bitwise operation with assignment.

For example, the expression a+=b has the same effect of performing a+b first and then assigning the result back to the variable a.

Similarly, the expression a<<=b has the same effect of performing a<<b first and then assigning the result back to the variable a.

Here is a C program that demonstrates the use of assignment operators in C:

When you compile and execute the above program, it produces the following result −

cppreference.com

Move assignment operator.

A move assignment operator is a non-template non-static member function with the name operator = that can be called with an argument of the same class type and copies the content of the argument, possibly mutating the argument.

[ edit ] Syntax

For the formal move assignment operator syntax, see function declaration . The syntax list below only demonstrates a subset of all valid move assignment operator syntaxes.

[ edit ] Explanation

The move assignment operator is called whenever it is selected by overload resolution , e.g. when an object appears on the left-hand side of an assignment expression, where the right-hand side is an rvalue of the same or implicitly convertible type.

Move assignment operators typically "steal" the resources held by the argument (e.g. pointers to dynamically-allocated objects, file descriptors, TCP sockets, I/O streams, running threads, etc.), rather than make copies of them, and leave the argument in some valid but otherwise indeterminate state. For example, move-assigning from a std::string or from a std::vector may result in the argument being left empty. This is not, however, a guarantee. A move assignment is less, not more restrictively defined than ordinary assignment; where ordinary assignment must leave two copies of data at completion, move assignment is required to leave only one.

[ edit ] Implicitly-declared move assignment operator

If no user-defined move assignment operators are provided for a class type, and all of the following is true:

  • there are no user-declared copy constructors ;
  • there are no user-declared move constructors ;
  • there are no user-declared copy assignment operators ;
  • there is no user-declared destructor ,

then the compiler will declare a move assignment operator as an inline public member of its class with the signature T & T :: operator = ( T && ) .

A class can have multiple move assignment operators, e.g. both T & T :: operator = ( const T && ) and T & T :: operator = ( T && ) . If some user-defined move assignment operators are present, the user may still force the generation of the implicitly declared move assignment operator with the keyword default .

The implicitly-declared (or defaulted on its first declaration) move assignment operator has an exception specification as described in dynamic exception specification (until C++17) noexcept specification (since C++17) .

Because some assignment operator (move or copy) is always declared for any class, the base class assignment operator is always hidden. If a using-declaration is used to bring in the assignment operator from the base class, and its argument type could be the same as the argument type of the implicit assignment operator of the derived class, the using-declaration is also hidden by the implicit declaration.

[ edit ] Implicitly-defined move assignment operator

If the implicitly-declared move assignment operator is neither deleted nor trivial, it is defined (that is, a function body is generated and compiled) by the compiler if odr-used or needed for constant evaluation (since C++14) .

For union types, the implicitly-defined move assignment operator copies the object representation (as by std::memmove ).

For non-union class types, the move assignment operator performs full member-wise move assignment of the object's direct bases and immediate non-static members, in their declaration order, using built-in assignment for the scalars, memberwise move-assignment for arrays, and move assignment operator for class types (called non-virtually).

As with copy assignment, it is unspecified whether virtual base class subobjects that are accessible through more than one path in the inheritance lattice, are assigned more than once by the implicitly-defined move assignment operator:

[ edit ] Deleted move assignment operator

The implicitly-declared or defaulted move assignment operator for class T is defined as deleted if any of the following conditions is satisfied:

  • T has a non-static data member of a const-qualified non-class type (or possibly multi-dimensional array thereof).
  • T has a non-static data member of a reference type.
  • T has a potentially constructed subobject of class type M (or possibly multi-dimensional array thereof) such that the overload resolution as applied to find M 's move assignment operator
  • does not result in a usable candidate, or
  • in the case of the subobject being a variant member , selects a non-trivial function.

A deleted implicitly-declared move assignment operator is ignored by overload resolution .

[ edit ] Trivial move assignment operator

The move assignment operator for class T is trivial if all of the following is true:

  • It is not user-provided (meaning, it is implicitly-defined or defaulted);
  • T has no virtual member functions;
  • T has no virtual base classes;
  • the move assignment operator selected for every direct base of T is trivial;
  • the move assignment operator selected for every non-static class type (or array of class type) member of T is trivial.

A trivial move assignment operator performs the same action as the trivial copy assignment operator, that is, makes a copy of the object representation as if by std::memmove . All data types compatible with the C language (POD types) are trivially move-assignable.

[ edit ] Eligible move assignment operator

Triviality of eligible move assignment operators determines whether the class is a trivially copyable type .

[ edit ] Notes

If both copy and move assignment operators are provided, overload resolution selects the move assignment if the argument is an rvalue (either a prvalue such as a nameless temporary or an xvalue such as the result of std::move ), and selects the copy assignment if the argument is an lvalue (named object or a function/operator returning lvalue reference). If only the copy assignment is provided, all argument categories select it (as long as it takes its argument by value or as reference to const, since rvalues can bind to const references), which makes copy assignment the fallback for move assignment, when move is unavailable.

It is unspecified whether virtual base class subobjects that are accessible through more than one path in the inheritance lattice, are assigned more than once by the implicitly-defined move assignment operator (same applies to copy assignment ).

See assignment operator overloading for additional detail on the expected behavior of a user-defined move-assignment operator.

[ edit ] Example

[ edit ] defect reports.

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

[ edit ] See also

  • constructor
  • converting constructor
  • copy assignment
  • copy constructor
  • default constructor
  • aggregate initialization
  • constant initialization
  • copy initialization
  • default initialization
  • direct initialization
  • list initialization
  • reference initialization
  • value initialization
  • zero initialization
  • move constructor
  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 11 January 2024, at 19:29.
  • This page has been accessed 755,943 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

  • 90% Refund @Courses
  • Standard Template Library
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators

Related Articles

  • Solve Coding Problems
  • Vector in C++ STL
  • Initialize a vector in C++ (7 different ways)

Commonly Used Methods

  • vector::begin() and vector::end() in C++ STL
  • vector::empty() and vector::size() in C++ STL
  • vector::operator= and vector::operator[ ] in C++ STL
  • vector::front() and vector::back() in C++ STL
  • vector::push_back() and vector::pop_back() in C++ STL
  • vector insert() Function in C++ STL
  • vector emplace() function in C++ STL

vector :: assign() in C++ STL

  • vector erase() and clear() in C++

Other Member Methods

  • vector max_size() function in C++ STL
  • vector capacity() function in C++ STL
  • vector rbegin() and rend() function in C++ STL
  • vector :: cbegin() and vector :: cend() in C++ STL
  • vector::crend() & vector::crbegin() with example
  • vector : : resize() in C++ STL
  • vector shrink_to_fit() function in C++ STL
  • Using std::vector::reserve whenever possible
  • vector data() function in C++ STL
  • 2D Vector In C++ With User Defined Size
  • Passing Vector to a Function in C++
  • How does a vector work in C++?
  • How to implement our own Vector Class in C++?
  • Advantages of vector over array in C++

Common Vector Programs

  • Sorting a vector in C++
  • How to reverse a Vector using STL in C++?
  • How to find the minimum and maximum element of a Vector using STL in C++?
  • How to find index of a given element in a Vector in C++

vector:: assign() is an STL in C++ which assigns new values to the vector elements by replacing old ones. It can also modify the size of the vector if necessary.

The syntax for assigning constant values: 

Program 1: The program below shows how to assign constant values to a vector 

The syntax for assigning values from an array or list: 

Program 2: The program below shows how to assign values from an array or list 

The syntax for modifying values from a vector  

Program 3: The program below shows how to modify the vector 

Time Complexity – Linear O(N)

Syntax for assigning values with initializer list:

Program 4:The program below shows how to assign a vector with an initializer list.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now !

Please Login to comment...

  • poulami21ghosh
  • utkarshgupta110092

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Assignment Operators in C » PREP INSTA

    vector assignment operator c

  2. Assignment Operators in C

    vector assignment operator c

  3. C programming +=

    vector assignment operator c

  4. Assignment Operators in C++

    vector assignment operator c

  5. Assignment Operators in C Example

    vector assignment operator c

  6. C++ Operators

    vector assignment operator c

VIDEO

  1. Lecture 74||Size of Operator||C programming Tutorials||Complete Playlist||Placements||

  2. C++

  3. Vector Painting Assignment

  4. Decrement Operator In C Complete Explanation #decrementOperatorInC

  5. Assignment Operator│C programming│Part# 15│Learn CSE Malayalam

  6. Fundamentals Pen Tool Vector Assignment

COMMENTS

  1. c++

    7 Assignment operator will do the right thing. The way you've written copy, it'll mess up if v1 is larger than v2. - jrok Feb 20, 2013 at 10:36 5 If v1 is not required after the copy you could just v2.swap (v1);. - hmjd Feb 20, 2013 at 10:38 1 Write what you want to do. If you want to assign one vector to another, write that. - Alex Chamberlain

  2. vector::operator= and vector::operator [ ] in C++ STL

    This operator is used to assign new contents to the container by replacing the existing contents. It also modifies the size according to the new contents. Syntax : vectorname1 = (vectorname2) Parameters : Another container of the same type.

  3. ::operator=

    <vector> std:: vector ::operator= C++98 C++11 copy (1) vector& operator= (const vector& x); Assign content Assigns new contents to the container, replacing its current contents, and modifying its size accordingly. C++98 C++11 Copies all the elements from x into the container.

  4. std::vector<T,Allocator>::operator=

    1) Copy assignment operator. Replaces the contents with a copy of the contents of other . If std::allocator_traits<allocator_type>::propagate_on_container_copy_assignment::value is true, the allocator of *this is replaced by a copy of other. If the allocator of *this after assignment would compare unequal to its old value, the old allocator is ...

  5. std::vector<T,Allocator>::assign

    std::vector<T,Allocator>:: assign From cppreference.com < cpp ‎ | container ‎ | vector [edit template] C++ Compiler support Freestanding and hosted Language Standard library Standard library headers Named requirements Feature test macros (C++20) Language support library Concepts library (C++20) Metaprogramming library (C++11) Diagnostics library

  6. Copy assignment operator

    the copy assignment operator selected for every direct base of T is trivial; the copy assignment operator selected for every non-static class type (or array of class type) member of T is trivial. A trivial copy assignment operator makes a copy of the object representation as if by std::memmove. All data types compatible with the C language (POD ...

  7. ::assign

    Complexity Linear on initial and final sizes (destructions, constructions). Additionally, in the range version (1), if InputIterator is not at least of a forward iterator category (i.e., it is just an input iterator) the new capacity cannot be determined beforehand and the operation incurs in additional logarithmic complexity in the new size (reallocations while growing).

  8. std::vector::operator=

    2) Move assignment operator. Replaces the contents with those of other using move semantics (i.e. the data in other is moved from other into this container).other is in a valid but unspecified state afterwards. If std::allocator_traits<allocator_type>::propagate_on_container_move_assignment() is true, the target allocator is replaced by a copy of the source allocator.

  9. c++

    Does std::vector use the assignment operator of its value type to push_back elements? Ask Question Asked 13 years, 5 months ago Modified 5 years, 5 months ago Viewed 8k times 12 If so, why? Why doesn't it use the copy constructor of the value type? I get the following error:

  10. Move Constructors and Move Assignment Operators (C++)

    This topic describes how to write a move constructor and a move assignment operator for a C++ class. A move constructor enables the resources owned by an rvalue object to be moved into an lvalue without copying. For more information about move semantics, see Rvalue Reference Declarator: &&. This topic builds upon the following C++ class ...

  11. ::operator []

    Returns a reference to the element at position n in the vector container. A similar member function, vector::at, has the same behavior as this operator function, except that vector::at is bound-checked and signals if the requested position is out of range by throwing an out_of_range exception. Portable programs should never call this function with an argument n that is out of range, since this ...

  12. Assignment operators

    Assignment operators modify the value of the object. Syntax Over load able Prototype examples (for replaces the contents of the object is not modified). For class types, this is performed in a special member function, described in For non-class types, copy and move assignment are indistinguishable and are referred to as

  13. Improvements: Overloaded assignment operator

    Here is how we code a proper assignment operator: Let's look at how this works, starting with the declaration: . This declaration has a scope only through the end of the block, which in this case is just the one line. Improvements: Code placement Simple Classes: myvector.h Carleton DeTar 2007-08-17 Improvements: Overloaded assignment operator

  14. Assignment Operators in C

    The following table lists the assignment operators supported by the C language − Example Try the following example to understand all the assignment operators available in C − Live Demo

  15. What operation on a C++ vector leads to assignment operator call?

    1 You could instrument your own move assignment and copy assignment operators on MyClass to find out! (Assuming that you want info on both.) As pointed out by @underscore_d, it will also depend on whether or not you have move/copy ctors and move/copy assignment operators. E.g.

  16. Assignment Operators in C

    1. "=": This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. Example: a = 10; b = 20; ch = 'y'; 2. "+=": This operator is combination of '+' and '=' operators.

  17. operator overloading

    In those situations where copy assignment cannot benefit from resource reuse (it does not manage a heap-allocated array and does not have a (possibly transitive) member that does, such as a member std::vector or std::string), there is a popular convenient shorthand: the copy-and-swap assignment operator, which takes its parameter by value (thus working as both copy- and move-assignment ...

  18. c++

    Vector and assignment operator Ask Question Asked 12 years, 7 months ago Modified 12 years, 7 months ago Viewed 3k times 0 I need to do a deep copy of a vector to a vector. Ex - vector<char> a; // add some things vector<char> b; a = b;

  19. Move assignment operator

    The move assignment operator is called whenever it is selected by overload resolution, e.g. when an object appears on the left-hand side of an assignment expression, where the right-hand side is an rvalue of the same or implicitly convertible type.. Move assignment operators typically "steal" the resources held by the argument (e.g. pointers to dynamically-allocated objects, file descriptors ...

  20. vector :: assign() in C++ STL

    vector:: assign () is an STL in C++ which assigns new values to the vector elements by replacing old ones. It can also modify the size of the vector if necessary. The syntax for assigning constant values: vectorname.assign (int size, int value) Parameters: size - number of values to be assigned value - value to be assigned to the vectorname

  21. c++

    Is this the correct move assignment operator? Vector &Vector::operator= (Vector &&v) { elem = v.elem; sz = v.sz; v.elem = nullptr; v.sz = 0; return *this; } How would I be able to check that a move and not a copy was made if both constructors exist? c++ arrays move-semantics copy-assignment Share Improve this question Follow