質問

I am developing an application where I define multiple algorithms to work on an array of data, with the generic form:

Apply [algorithm[k]] to data at [i] and save at [o]

Narrowing to my doubt:

a) It's possible that the input and output are the same object, like when applying Gaussian filter to an image.

b) It's possible that the algorithm resolve to an no-op, like when interpolating an array of data to other of the same size.

When (a) and (b) happens at the same time, the following part of the algorithm

o[output_position]=process(i[input_position]);

Will resolute to

o[output_position]=o[output_position];

Is this safe?


Some quite-not-polished reasoning:

I assume it is, mostly because (but i don't feel confident with this assumption) memory-to-memory moves resolves to memory-to-register-to-memory move.

It worked with some simple tests, but I don't have the knowledge to say to someone "look at my well-designed code".

I plan to compile with optimization flags and move on to other portions of the project, so I worry that somewhere in the future things go BOOM and there goes another nice day spent on the debugger to trace this self-assignment.

Thanks in advance.

役に立ちましたか?

解決

This depends entirely on the type of o[output_position]. If it implements the assignment operator correctly, then it's fine. A correctly implemented assignment operator always works fine with self-assignment.

The idiomatic implementation of the assignment operator in C++ uses the copy-and-swap idiom. This then implies correct self-assignment, even without the this != &other check you'll often see in other implementations.

他のヒント

While using basic types (int, float, char), your reasoning will be fine - any assignment is done by memory-register-memory which is fast enough.

When using objects you will need to correctly implement the assignment operator (operator=). This will most likely be done by checking, as you must, that you're not assigning an object to itself:

Object operator=(const Object& other) {
    if (&other == this) { return *this };

    // your assignment code here!
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top