我一直在探索 C++ 中移动构造函数的可能性,我想知道在下面的示例中利用此功能的一些方法是什么。考虑这段代码:
template<unsigned int N>
class Foo {
public:
Foo() {
for (int i = 0; i < N; ++i) _nums[i] = 0;
}
Foo(const Foo<N>& other) {
for (int i = 0; i < N; ++i) _nums[i] = other._nums[i];
}
Foo(Foo<N>&& other) {
// ??? How can we take advantage of move constructors here?
}
// ... other methods and members
virtual ~Foo() { /* no action required */ }
private:
int _nums[N];
};
Foo<5> bar() {
Foo<5> result;
// Do stuff with 'result'
return result;
}
int main() {
Foo<5> foo(bar());
// ...
return 0;
}
在上面的示例中,如果我们跟踪程序(使用 MSVC++ 2011),我们会看到Foo<N>::Foo(Foo<N>&&)
在构造时调用了foo
,这是所需的行为。但是,如果我们没有Foo<N>::Foo(Foo<N>&&)
,Foo<N>::Foo(const Foo<N>&)
则会被调用,这将执行冗余复制操作。
我的问题是,如代码中所述,对于这个使用静态分配的简单数组的特定示例,有没有办法利用移动构造函数来避免这种冗余副本?