在移动分配操作员里面调用一个d-tor好习惯吗?
这里有一些示例代码:
VectorList &operator = (VectorList &&other){
~VectorList(); // if this is not a good practice,
// I will need to paste whole d-tor here.
_buffer = std::move(other._buffer );
_dataCount = std::move(other._dataCount );
_dataSize = std::move(other._dataSize );
other._clear();
return *this;
}
Run Code Online (Sandbox Code Playgroud)
我应该使用此代码,还是应该使用swap()与移动构造对象?
我不明白移动赋值是否能够/自由地改变变量x的地址并使所有指针和引用存储&x无效.我认为这是假的,因为默认的移动分配移动每个成员并保留这个指针,但它是否有保证?
编辑:示例
int x(1), y(2);
int& ref(x);
x = std::move(y);
// ref still valid ?
Run Code Online (Sandbox Code Playgroud) 考虑以下:
class Example : boost::noncopyable
{
HANDLE hExample;
public:
Example()
{
hExample = InitializeHandle();
}
~Example()
{
if (hExample == INVALID_HANDLE_VALUE)
{
return;
}
FreeHandle(hExample);
}
Example(Example && other)
: hExample(other.hExample)
{
other.hExample = INVALID_HANDLE_VALUE;
}
Example& operator=(Example &&other)
{
std::swap(hExample, other.hExample); //?
return *this;
}
};
Run Code Online (Sandbox Code Playgroud)
我的想法是析构函数将很快在"其他"上运行,因此我不必通过使用swap在移动赋值运算符中再次实现我的析构函数逻辑.但我不确定这是一个合理的假设.这会"好"吗?
我需要一些帮助来理解移动赋值运算符的继承过程。对于给定的基类
class Base
{
public:
/* Constructors and other utilities */
/* ... */
/* Default move assignment operator: */
Base &operator=(Base &&) = default;
/* One can use this definition, as well: */
Base &operator=(Base &&rhs) {std::move(rhs); return *this;}
/* Data members in Base */
/* ... */
};
class Derived : public Base
{
public:
/* Constructors that include inheritance and other utilities */
/* ... */
Derived &operator=(Derived &&rhs);
/* Additional data members in Derived */
/* …Run Code Online (Sandbox Code Playgroud) 作为此问题的扩展,我正在尝试正确设置我的移动分配。
我有以下代码:
// copy assignment operator
LinkedList<T>& operator= (LinkedList<T> other) noexcept
{
swap(*this, other);
return *this;
}
// move assignment operator
LinkedList<T>& operator= (LinkedList<T>&& other) noexcept
{
swap(*this, other);
return *this;
}
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试使用它时,我的代码无法编译。
首先一些代码:
LinkedList<int> generateLinkedList()
{
LinkedList<int> List;
List.add(123);
return List;
}
int main()
{
LinkedList<int> L;
L = generateLinkedList();
^ get an error here...
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
main.cpp(24):错误C2593:'operator ='不明确
linkedlist.h(79):注意:可以是'LinkedList&LinkedList :: operator =(LinkedList &&)noexcept'(指向移动分配运算符)
linkedlist.h(63):注意:或'LinkedList&LinkedList :: operator =(LinkedList)noexcept'(指向副本分配运算符)
main.cpp(24):注意:在尝试匹配参数列表'(LinkedList,LinkedList)'时
我的移动分配运算符是错误的,还是使用错误的方式?
我在 GCC、Clang 和 MSVC 中做了一些测试,发现emplace_back永远不会在包含的类上调用赋值运算符。它仅在重新分配时调用复制或移动构造函数。标准是否以某种方式保证这种行为?
用例是我有一些类按顺序存储在一个数字中,该数字只会随着时间的推移而增长,直到整个向量被破坏。我很乐意从赋值运算符中清除我的代码。
c++ allocation vector move-constructor move-assignment-operator