i have three pointers to three objects:
MyClass* a = new MyClass(...);
MyClass* b = new MyClass(...);
MyClass* c = new MyClass(...);
Now i want to specify an operator in MyClass so that I can do:
a = b*c;
So a,b, and c are already existing large objects which i do not want to make any additional copies of. I want to do the multiplication and directly write the result 'a'.
1) Is this even possible with c++ operators? 2) Could someone give me some hints at the syntax? (i'm a bit new to operators..)
Grateful for any help.
If you wrote operator*
for MyClass
.
MyClass* a = new MyClass(...);
MyClass* b = new MyClass(...);
MyClass* c = new MyClass(...);
you should use it like below:
*a = (*b) * (*c);
And you can not do it for pointers. For example this is impossible :
MyClass *operator*(const MyClass *a, const MyClass *b) // Impossible
{
...
}
Because the operator definition must have an argument of MyClass
.
You really don't want to do this. Sticking with the standard way of defining operators for values and not pointers-to-values will make everything a lot cleaner and easier to maintain.
EDIT As aschepler points out in the comments you can't even do this. At least one of the arguments must be of a class type or a reference to a class.
If you want to avoid huge copy operations, you should use C++11 move semantics or emulate them through something like a MoveProxy
or the Boost.Move support-library.
Example code:
// loads of memory with deep-copy
struct X {
int* mem;
X() : mem(new int[32]) { }
// deep-copy
X(const X& other)
: mem(new int[32]) { std::copy(other.mem, other.mem+32, this.mem); }
~X() { delete[] mem; }
X& operator=(const X& other) { std::copy(other.mem, other.mem+32, this.mem); return *this; }
X(X&& other) : mem(other.mem) { other.mem = nullptr; }
X& operator=(X&& other) { delete[] mem; this.mem = other.mem; other.mem = nullptr; return this; }
friend void swap(const X& x, const X& y)
{ std::swap(x.mem, y.mem); }
friend
X operator*(const X& x, const X& y)
{ return X(); }
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.