实施B = F(A),与已经定义B和A阵列和B [英] Implementing B=f(A), with B and A arrays and B already defined

查看:194
本文介绍了实施B = F(A),与已经定义B和A阵列和B的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个数组 B 已经已经定义,并在C ++ code的地方使用。现在,假设我有另一个数组 A 已被定义并初始化。我想创建一个函数˚F的变换 A (例如,FFT)和我想要的结果改造被分配到 (当然B, A 的改造下乙将改变其值)。我想保持语法做的一切,

Suppose I have an array B that has been already defined and used somewhere in a C++ code. Now, suppose that I have another array A that has been defined and initialized. I want to create a function f that transforms A (for example, an FFT) and I want that the result of the transformation is assigned to B (of course, following the transformation of A, B will change its values). I want to do all that by keeping the syntax

B=f(A);

,即没有通过 B 的地址作为参数传递给˚F。它是可能的:

namely, without passing the address of B as an argument to f. Is it possible:


  1. 没有创建临时的?

  2. 在创建临时的,但是没有内存泄漏?

感谢您。

编辑:提供了以下解答在解决方案概述

由于RIAD,詹姆斯甘孜,沙赫巴兹和Razispio了他们的答案。

Thanks to RiaD, James Kanze, Shahbaz and Razispio for their answers.

我要问,需要 A B 来是为了提高效率数组类的对象和有效性。此外,在标准的实施,例如,用装有复制构造一个数组类,如 B = F(A)语法; 将需要临时创建。然而,应当提到的是临时不一定是限制,因为许多编译器将能够的Elid额外临时。与此相反,如语法F(A,B); 将避免临时。使用的前pression模板的该解决方案使语法 B = F(A);而内部使用 F( A,B); ,使得使用的临时忽略不计的。一种有效的替代解决方案是使用移动赋值操作符,例如见

What I'm asking requires A and B to be objects of an array class in order to gain efficiency and effectiveness. Also, in a "standard" implementation, e.g., with an array class equipped with a copy constructor, a syntax like B=f(A); would require the creation of temporaries. It should be however mentioned that temporaries are not necessarily a limitation, since many compilers would be able to elide the extra temporaries. Opposite to this, a syntax like f(A,B); would avoid temporaries. The solution using expression templates enables the syntax B=f(A); while internally using f(A,B);, making the use of temporaries negligible. An efficient alternative solution would be using move assignment operators, see for example

移动语义在C ++ 11 右值引用

有关详细信息,请参阅答案好心如下。

For details, see the answers kindly provided below.

推荐答案

它使用的std ::矢量的std ::最简单的方法阵列

例如:

vector<int> f(const vector<int>& a) {
   return a;
}

b = f(a);

其实,你不必使用这个类的一个存储,您可以使用自己的类,有运算符=

YourClass& operator = (const vector<int>&/* there will be returned value of f, it may be std::array, std::vector or your own class.*/ v) {
    //fill it here.
    return *this;
}

您也可以提供移动构造,以避免不必要的复制。

You may also provide move constructor for it to avoid unnecessary copying.

例如:

class Array {
    int* data;   
    YourClass& operator = (YourClass&& v) {
        swap(v.data, data);
    }
}

YourClass f(const YourClass& a) {
   //
}

Array a,b;
b = f(a);

这篇关于实施B = F(A),与已经定义B和A阵列和B的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆