我一直在探索在C++中使用Move Constructors的可能性,我想知道在下面这样的示例中,有什么方法可以利用这个特性。考虑下面的代码:
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>&)
,这将执行冗余的复制操作。
我的问题是,正如代码中所指出的,对于这个使用静态分配的简单数组的特定示例,有没有办法利用move构造函数来避免这种冗余复制?
https://stackoverflow.com/questions/7885479
复制相似问题