简体   繁体   English

C ++ 11中的有效算术运算符重载

[英]Efficient arithmetic operator overloading in C++11

I have a POD struct that has a number of members, and I would like to know the most efficient way in C++11 to implement its arithmetic operators. 我有一个具有许多成员的POD结构,我想知道C ++ 11中实现其算术运算符的最有效方法。

This struct is meant to be used in place of primitives in a mathematical context; 该结构旨在在数学上下文中代替基本体。 for example: 例如:

template<typename Double>
Double calcSomething(const Double& d0, const Double& d1, const Double& d2)
{
    return d0*d1 + 3*d2 - 6;
}

Where Double is either just a normal double , or is a POD struct with all the relevant overloaded operators: 其中Double只是普通double ,或者是带有所有相关重载运算符的POD结构:

struct MyDouble
{
    MyDouble(double a, double b) : _a(a), _b(b) {}
    double _a;
    double _b;
};
MyDouble operator+(const MyDouble& d0, const MyDouble& d1) 
{
    return MyDouble(d0._a + d1._a, d0._b + d1._b);
}

Is there a really nice, efficient way to implement this in C++11 using move constructors and rvalue references? 在C ++ 11中,是否有使用移动构造函数和右值引用实现的一种非常不错,高效的方法? Keep in mind that MyDouble could be a large POD struct (ie not just two doubles). 请记住, MyDouble可能是一个大型POD结构(即不只是两个double)。

I would like to keep the discussion about structs that do not have pointers to heap-allocated memory. 我想继续讨论没有指向堆分配内存的指针的结构。

If a struct doesn't own any other objects or resources, then move semantics and copy semantics are identical. 如果一个结构不拥有任何其他对象或资源,则移动语义和复制语义是相同的。 Even a move constructor or move assignment operator needs to copy all data members to the target object. 甚至移动构造函数或移动分配运算符也需要将所有数据成员复制到目标对象。 It just doesn't have to perform a deep copy, ie owned sub-objects are simply transferred to the target object, instead of being copied. 只是不必执行深层复制,即,将拥有的子对象简单地转移到目标对象,而无需复制。

If your struct is truly huge, you can create a holder type which contains a pointer to a heap-allocated instance (using scoped_ptr, preferably). 如果您的结构确实很大,则可以创建一个holder类型,该类型包含指向堆分配实例的指针(最好使用scoped_ptr)。 You can then support move on that holder type - actually, if you manage the actual instance with scoped_ptr, you'll get move support automatically, I think. 然后,您可以支持该持有人类型的移动-实际上,如果您使用scoped_ptr管理实际实例,我认为您将自动获得移动支持。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM