gpt4 book ai didi

c++ - 交换两个类实例的最安全方法

转载 作者:行者123 更新时间:2023-11-30 04:23:23 24 4
gpt4 key购买 nike

使用swap交换两个类实例,有时会报错。

#include <iostream>
#include <string>
using namespace std;

#include <cstring>
class Buffer {
public:
Buffer(const string& s): buffer(s) {}
string buffer;
};

template<class _Tx>
void SWAP(_Tx& a, _Tx& b) {
size_t size = sizeof(_Tx);
char buffer[size];
memcpy(buffer, &a, size);
memcpy(&a, &b, size);
memcpy(&b, buffer, size);
}

int main() {
Buffer a("This is a"), b("This is b");
swap(a,b);
cout << a.buffer << endl;

SWAP(a,b);
cout << b.buffer << endl;
return 0;
}

std::swap 会做这样的事情:

template<class _Tx>
void swap(_Tx &a, _Tx &b) {
_Tx t = a;
a = b;
b = t;
}

_Tx t = a;会调用_Tx的复制构造函数,在本例中是Buffer::Buffer(Buffer &e) .此方法尝试分配一些内存,这可能会导致一些错误。

我尝试使用另一种方法代替 std::swap:

template<class _Tx>
void SWAP(_Tx& a, _Tx& b) {
char buffer[sizeof(_Tx)];
memcpy(buffer, &a, sizeof(_Tx));
memcpy(&a, &b, sizeof(_Tx));
memcpy(&b, buffer, sizeof(_Tx));
}

这是一种安全的方式吗???

更新std::swap 在 c++0x 中可能是安全的。这是比较:c99c++0x


引用 what-is-the-copy-and-swap-idiom 感谢 Donal Fellows 的提醒

最佳答案

问题出在动态分配的指针buffer上,为什么不用std::string

复制构造函数签名是:

Buffer(const Buffer &e) 

现在你交换对象:

int main(int agrc, char* argv[])
{
Buffer a("This is a"), b("This is b");
std::swap(a,b);
}

std::swap 代码应该比你的 SWAP 代码更快

template<class _Ty> inline
void swap(_Ty& _Left, _Ty& _Right)
{ // exchange values stored at _Left and _Right
_Ty _Tmp = _Move(_Left);
_Left = _Move(_Right);
_Right = _Move(_Tmp);
}

关于c++ - 交换两个类实例的最安全方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13393928/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com