Alternative for the = sign

I was asked to implement C ++ code to do the x = y assignment, unsigned = and without functions. I used memcpy:

int main(int argc, char *argv[])
    int x(5),y(3);
    return 0;


any other general solutions?



source to share

5 answers

If x

and y

are considered int:

while (x < y) {
while (y < x) {




I'm not sure what is meant (5)

and (3)

how person C is, but if they are just integers, then how about:

x |= y; // all bits set in y now definitely set in x
x &= y; // all bits not set in y now definitely not set in x


Or, as per Oli Charlworth's comment below, if you don't want the = symbol, then:

x or_eq y; // all bits set in y now definitely set in x
x and_eq y; // all bits not set in y now definitely not set in x




In any real context, this isn't very useful, but it at least solves the "problem" by its own rules:

int main(int argc, char* argv[])
    int y(5);
    int x(y);

    std::cout << x << " " << y << std::endl;

    return 0;




Warning: this is getting ugly ... firmly in fragile hacker land; -P.

An assignment to an arbitrary type sometimes has to call a function — the assignment operator or the [copy] constructor. Placement new

is a statement, not a function call, although you may need to pass parameters to the constructor. To recreate the object as a whole, you need to know that it was destroyed beforehand, which requires a function call but not for assignment - is that allowed or not? :-) Anyway, the idea still breaks down if reconstruction can throw, since the destructor can be called a second time on an already destroyed object. In practice, you can write a destructor to make this safe (e.g. NULL pointers afterdelete

) or don't throw the constructor, but this behavior is undefined and not really general (the kinds of complications you might expect: the virtual dispatch pointer may have already been returned to the base class from destructors that were deleted, virtual bases were destroyed, etc. .) ....

T x = a, y = b;  // "background"

// hacked pseudo-assignment
x.~T(); // should make this function call though, if it exists!
new (&x)(y);  // x = y


Another bizaare approach that may or may not be accepted, depending on whether indirect function calls are allowed:

std::stringstream ss;
ss << y;
ss >> y;


More generally, the only mutating operators that don't include the "=" sign in their typical form are placement new

, ++

and --

, and alternative forms such as xor_eq

have also been discussed in other answers, so I'm thinking about it ....



Oneliner, inspired by Michael Burr: x += (y-x);

. Works for all numeric types, O (1) even std::complex

, as well as random iterators (including pointers).



All Articles