Home  >  Article  >  Backend Development  >  Is Self Move Assignment Possible with Rvalue Reference Parameters in C 11?

Is Self Move Assignment Possible with Rvalue Reference Parameters in C 11?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-10 13:52:02651browse

Is Self Move Assignment Possible with Rvalue Reference Parameters in C  11?

Self Move Assignment and the Standard Library

In C 11, the standard library provides certain guarantees regarding self move assignment. According to the standard, if a function argument binds to an rvalue reference parameter, the implementation can assume that the parameter is a unique reference to that argument.

Consider the following function:

template<class T>
std::vector<T> selfAssign(std::vector<T> v) {
  v = std::move(v);
  return v;
}

Since the vector argument binds to an rvalue reference parameter, the implementation of std::vector::operator=(vector&& other) can assume that other is a prvalue. Consequently, self-move-assignment is not possible for v in the selfAssign function.

The standard dictates that an rvalue reference parameter can be assumed to be a prvalue, thus precluding the possibility of self-move-assignment in such cases. It is likely that the vector passed to the selfAssign function will be left in a resource-less state or undergo a no-op if it already has 0 capacity.

However, the latest working draft of the standard, N4618, slightly modifies these requirements. Specifically, it states that, if t and rv do not refer to the same object, then after the assignment 't = rv', t may only need to contain the equivalent value of rv prior to the assignment. Regardless, the state of rv remains unspecified after the assignment.

The above is the detailed content of Is Self Move Assignment Possible with Rvalue Reference Parameters in C 11?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn