使用这种swap实现的最大威胁是什么?除了线程安全和差的优化.什么时候失败(反例)?
template<typename T>
void swapViaMemory(T& left, T& right) {
if(&left == &right) { return ; }
unsigned int tSize = sizeof(T);
unsigned char* lPtr = reinterpret_cast<unsigned char*>(&left);
unsigned char* rPtr = reinterpret_cast<unsigned char*>(&right);
for(unsigned int i = 0; i < tSize; ++i) {
*(lPtr + i) ^= *(rPtr + i);
*(rPtr + i) ^= *(lPtr + i);
*(lPtr + i) ^= *(rPtr + i);
}
}
Run Code Online (Sandbox Code Playgroud)
对不起语法错误和拼写错误(=
这是go中的示例代码:
package main
import "fmt"
func mult32(a, b float32) float32 { return a*b }
func mult64(a, b float64) float64 { return a*b }
func main() {
fmt.Println(3*4.3) // A1, 12.9
fmt.Println(mult32(3, 4.3)) // B1, 12.900001
fmt.Println(mult64(3, 4.3)) // C1, 12.899999999999999
fmt.Println(12.9 - 3*4.3) // A2, 1.8033161362862765e-130
fmt.Println(12.9 - mult32(3, 4.3)) // B2, -9.536743e-07
fmt.Println(12.9 - mult64(3, 4.3)) // C2, 1.7763568394002505e-15
fmt.Println(12.9 - 3*4.3) // A4, 1.8033161362862765e-130
fmt.Println(float32(12.9) - float32(3)*float32(4.3)) // B4, -9.536743e-07
fmt.Println(float64(12.9) - float64(3)*float64(4.3)) // C4, 1.7763568394002505e-15
}
Run Code Online (Sandbox Code Playgroud)
A1,B1和C1行之间的结果差异是可以理解的。但是,从A2到C2的魔力来了。B2和C2的结果都不匹配A2行的结果。x2行(x …
以下是C++源代码.该代码具有HumanBeing类以及Display和verify函数.每个函数都打印语句.
#include <iostream>
using namespace std;
class HumanBeing {
public:
void display() {
cout << "hello aam a human being" << endl;
}
void print() {
cout << "verify print" << endl;
}
};
int main() {
HumanBeing vamshi;
vamshi.display();
vamshi.print();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是上述c ++代码的相应汇编代码
.file "verify.cpp"
.local _ZStL8__ioinit
.comm _ZStL8__ioinit,1,1
.section .rodata
.LC0:
.string "hello aam a human being"
.section .text._ZN10HumanBeing7displayEv,"axG",@progbits,_ZN10HumanBeing7displayEv,comdat
.align 2
.weak _ZN10HumanBeing7displayEv
.type _ZN10HumanBeing7displayEv, @function
_ZN10HumanBeing7displayEv:
.LFB971:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16 …Run Code Online (Sandbox Code Playgroud) assembly ×1
c++ ×1
constructor ×1
destructor ×1
go ×1
ieee-754 ×1
memory ×1
swap ×1
templates ×1
xor ×1