其他分享
首页 > 其他分享> > c – 标准库对自动分配的保证是什么?

c – 标准库对自动分配的保证是什么?

作者:互联网

C 11标准对标准库相关的自动分配有什么看法?更具体的是,什么,如果有的话,保证selfAssign的作用是什么?

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

解决方法:

17.6.4.9函数参数[res.on.arguments]

1 Each of the following applies to all arguments to functions defined
in the C++ standard library, unless explicitly stated otherwise.

  • If a function argument binds to an rvalue reference parameter, the implementation may assume that this parameter is a unique reference to
    this argument. [ Note: If the parameter is a generic parameter of the
    form T&& and an lvalue of type A is bound, the argument binds to an
    lvalue reference (14.8.2.1) and thus is not covered by the previous
    sentence. — end note ] [ Note: If a program casts an lvalue to an
    xvalue while passing that lvalue to a library function (e.g. by
    calling the function with the argument move(x)), the program is
    effectively asking that function to treat that lvalue as a temporary.
    The implementation is free to optimize away aliasing checks which
    might be needed if the argument was anlvalue. —endnote]

因此,允许std :: vector< T,A> :: operator =(vector&& other)的实现假设其他是prvalue.如果其他是prvalue,那么自动移动分配是不可能的.

可能发生的事情:

v将保持无资源状态(0容量).如果v已经有0容量,那么这将是一个无操作.

更新

已修改latest working draft, N4618以清楚地表明在MoveAssignable要求中的表达式:

t = rv

(其中rv是一个rvalue),如果t和rv不引用同一个对象,则t只需要在赋值之前为rv的等效值.而且无论如何,rv的状态在分配后都没有指定.还有一个说明需要进一步说明:

rv must still meet the requirements of the library component that is using it, whether or not t and rv refer to the same object.

标签:c,c11,stl,move-semantics
来源: https://codeday.me/bug/20190916/1808663.html