gpt4 book ai didi

c++ - 使用无分配交换有什么明显的缺点吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:51:41 25 4
gpt4 key购买 nike

我正在实现(出于培训目的)冒泡排序模板函数:

template<typename iterInput,
typename predicate>
void BubbleSort(iterInput first1,iterInput last1,predicate func)
{
bool swapped(false);
do
{
swapped = false;
iterInput begin = first1;
iterInput beginMinus = first1;
++begin;
for (;begin != last1; begin++,beginMinus++)
{
if (func(*beginMinus,*begin) )
{
std::swap(*beginMinus,*begin);
swapped = true;
}
}
}
while(swapped);
}

当我意识到这个函数不适用于没有赋值运算符的类时,比如这个(请原谅我的坏名字):

class NoCopyable
{
public:
explicit NoCopyable(int value) : value_(value) {}
NoCopyable(const NoCopyable& other) : value_(other.value_) {}
~NoCopyable() {}
bool operator<(const NoCopyable& other) { return value_ < other.value_; }
void setValue(int value) { value_ = value; }
std::ostream& print(std::ostream& os) const { return os << value_; }
private:
NoCopyable& operator=(const NoCopyable& other);
int value_;
};

std::ostream& operator<<(std::ostream& os, const NoCopyable& obj)
{
return obj.print(os);
}

struct PrintNoCopyable
{
void operator()(const NoCopyable& noCopyable) { std::cout << noCopyable << '\n'; }
};

编译器引发此错误 Error 1 error C2248: 'NoCopyable::operator =' : cannot access private member declared in class 'NoCopyable'

因此,我使用我的交换函数版本代替 std::swap 函数稍微修改了代码,这里是代码:

template<typename T1,
typename T2>
void noAssignmentSwap(T1& t1,T2& t2)
{
T1 temp(t1);
t1.~T1();
new (&t1) T1(t2);
t2.~T2();
new (&t2) T2(temp);
}

代码编译并给出正确的结果。但是我不完全确定,我记得 Sutter 的一篇文章建议您避免在整个生命周期内玩弄这些对象。这篇文章只是用玩火来警告你,实际上并没有给你任何真正的理由。如果 T1 或 T2 的复制构造函数可以抛出,我可以看到异常安全问题。但是,如果允许赋值运算符抛出,则在标准版本中存在同样的问题。

问题来了,你能看出这个版本的 swap 有什么可能的缺点吗?

干杯

最佳答案

除此之外,如果一个类没有赋值运算符,它的设计者可能并不打算将其交换。如果他们那样做了,他们可能也禁用了复制构造,因此您的新交换功能仍然无法工作。

至于您关于标准库容器不需要赋值的断言 - 只要您实际上不想对它们做任何有用的事情,那是正确的。此代码是否为您编译?

#include <vector>
using namespace std;

struct A {
private:
void operator=( const A &);
};

int main() {
vector <A> v;
v.push_back( A() );
v[0] = A(); // assignment needed here
}

我认为不会。

关于c++ - 使用无分配交换有什么明显的缺点吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6155148/

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