首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >移动构造函数和静态数组

移动构造函数和静态数组
EN

Stack Overflow用户
提问于 2011-10-25 14:33:22
回答 1查看 14.4K关注 0票数 28

我一直在探索在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构造函数来避免这种冗余复制?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7885479

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档