包含 boost::numeric::ublas::matrix的类的运算符重载
我有一个类,其中包含一些 boost::numeric::ublas::matrix 。我想重载该类的运算符 (+-*/=),以便我可以用一个语句对一组矩阵进行操作。
然而,这似乎需要我的类的临时实例来携带值而不修改原始类。这对我来说很有意义,但是,当我在函数中创建一个新实例并返回它时,我得到:
warning: reference to local variable 'temp' returned
我对 C++ 很陌生,并且运算符重载的示例似乎都返回新的临时对象。我还想避免实例化新矩阵的开销,这导致我循环遍历所有元素。我该怎么办?性能是一个问题。
I have a class which contains a few boost::numeric::ublas::matrix's within it. I would like to overload the class's operators (+-*/=) so that I can act on the set of matrices with one statement.
However this seems to require temporary instances of my class to carry values around without modifying the original class. This makes sense to me, however, when I create a new instance within the function and return it I get:
warning: reference to local variable ‘temp’ returned
I'm pretty new to c++ and the examples of operator overloading seem to all return new temporary objects. I would also like to avoid the overhead in instantiating new matrix's, which leads me towards looping over all elements. How should I go about this? Performance is a concern.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您已经在使用 boost,我强烈建议使用 boost::operators 以及您的示例。
您将获得几个好处:
If you're using boost already, I'd strongly suggest using boost::operators along with your example.
You'll get several benefits:
常规的运算符重载方式如下。 (我认为)
你的就地运算符被定义为成员,例如:
它只是在
*this
上做他们需要的事情:然后创建自由函数,并让复制在参数中完成
:返回值是const,因为这样做很奇怪:
同样,这样做也很奇怪:
尽管你对此会得到不同的意见。这就是您重用代码并自动为您完成复制的方式。非常简洁易读。
不过,就像尼尔和我上面所说的那样,如果您要创建新数据,那么在某些时候该数据需要有一个新的存放位置。尽可能使用变异运算符来避免这种情况,但有些事情根本无法逃脱。
这甚至可能不是问题。如果是,请尝试优化您的内存分配;这些可能是最慢的部分。我不确定,但我认为大多数 boost 类都允许您指定分配器。 boost 内存池库在这里可能有用。
The conventional way of operator overloading is as follows. (I think)
Your in-place operators are defined as members, such as:
Which simply do what they need on
*this
:Then make free functions, and let the copying be done in the arguments:
The return value is
const
because it's strange to do:In the same way it's strange to do:
Though you'll get differing opinions on that. This is how you reuse your code, and have the copy done for you automatically. Very terse and readable.
Like Neil and I said above, though, if you're creating new data, at some point that data needs to have a new place to stay. Use mutating operators when you can to avoid this, but some things simply cannot be escaped.
It might not even be a problem. If it is, try to optimize the memory allocations you have; these are likely the slowest part. I'm not sure, but I think most boost classes let you specify an allocator. The boost memory pool library may be useful here.