gpt4 book ai didi

c++ - 使用非指针数据成员 move 语义

转载 作者:行者123 更新时间:2023-11-28 00:00:20 25 4
gpt4 key购买 nike

可能已经有人询问并回答了这个问题,但我不知道要搜索什么。

如果数据成员定义了 move 赋值运算符, move 语义是否可以用于非指针数据成员?

假设我有一个类 M定义 M::operator=(M&&)像这样:

template <class T>
class M
{
public:
M()
{
mem_M = new T;
}

M& operator=(M&& src)
{
if (this != &src)
{
mem_M = src.mem_M;
src.mem_M = nullptr;
}
return *this;
}

private:
T* mem_M;
};

现在显然我可以上课了 C<T>像这样,使用不使用 T 的 move 构造函数的 move 赋值运算符:

template <class T>
class C
{
public:
C ()
{
mem_C = new T;
}
C (C&& rhs)
{
mem_C = rhs.mem_C;
rhs.mem_C = nullptr;
}

private:
T* mem_C;
};

但是,如果我想要 C<T>::mem_C 怎么办?不是指针而是普通成员,我将如何处理 C<T>::mem_C在 move 功能中?我当然可以调用 move 赋值运算符 T::operator=(T&&) move 归档 mem_C从一个实例到另一个实例,但如何正确重置 C 的实例传递给 C<T>::C(C&&)

这至少在我看来是错误的:

template <class T>
class C
{
public:
C ()
{
mem_C = T();
}
C (C<T>&& rhs)
{
mem_C = std::move(rhs.mem_C);
rhs.mem_C = T(); // ?? like this?
}

private:
T mem_C;
};

那么,在 move 函数中重置非指针数据成员的符合标准的方法是什么?

最佳答案

包含类型的 move 赋值/构造函数必须使对象处于“可接受”状态,无论该状态对该类型意味着什么。正在 move 的类型之外的任何内容都不应该负责维护对象的状态。

此外,您要确保在父 move 构造函数中调用包含类型的 move 构造函数,而不是调用包含类型的 move 赋值 就像你在你的例子中一样:

// move constructor calls move constructor of contained elements
C (C<T>&& rhs) : mem_c(std::move(rhs.mem_c))
{
// anything in here is using already-constructed data members
}

// move assignment calls move assignment of contained elements
C & operator=(C<T>&& rhs) {
mem_c = std::move(rhs.mem_c);
}

关于c++ - 使用非指针数据成员 move 语义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39563145/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com