我一直在探索在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构造函数来避免这种冗余复制?
发布于 2011-10-25 14:54:39
在这种情况下,它没有用处,因为int
没有移动构造器。
但是,如果这些字符串是字符串,那么它可能会很有用,例如:
template<unsigned int N>
class Foo {
public:
// [snip]
Foo(Foo<N>&& other) {
// move each element from other._nums to _nums
std::move(std::begin(other._nums), std::end(other._nums), &_nums[0]);
}
// [snip]
private:
std::string _nums[N];
};
现在,您可以避免将字符串复制到可以执行移动的位置。如果您完全省略所有的复制/移动构造函数,我不确定一个符合规范的C++11编译器是否会生成等价的代码,对不起。
(换句话说,我不确定是否专门定义了std::move
来对数组进行逐个元素的移动。)
https://stackoverflow.com/questions/7885479
复制相似问题