【发布时间】:2020-04-24 10:50:18
【问题描述】:
我有一个不应被复制而只能移动的对象,因此我试图确保函数返回对象的T&&。我的问题是对象在返回之前就被销毁了,我不知道如何正确地做到这一点。
#include <iostream>
class Foo
{public:
Foo() {
a = new int;
std::cout << a << '\n';
}
Foo(const Foo& other) = delete;
Foo(Foo&& other) {
a = other.a; other.a = nullptr;
}
~Foo() {
std::cout << a << '\n';
delete a;
}
void operator= (const Foo& other) = delete;
void operator= (Foo&& other) {
a = other.a;
other.a = nullptr;
}
int* a;
};
Foo&& createNewFoo()
{
return std::move(Foo());
}
int main()
{
Foo foo = createNewFoo(); // The pointer is deleted before this assigns to foo
}
【问题讨论】:
-
顺便说一句。
void operator=()看起来有点奇怪。我习惯了返回类型引用(即return *this;)。 Canonical implementations - Assignment operator -
继续 Scheff 所说的话。
void operator=()是合法且允许的,但它是非惯用的,这增加了使用该对象的任何其他开发人员的摩擦。因为它会以令人惊讶和不寻常的方式表现。这是一个建议,不是规则以通常的方式执行,可能有充分的理由进行非典型实施。
标签: c++ c++11 return move temporary-objects