- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在实现(出于培训目的)冒泡排序模板函数:
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/
通常当我请求线程转储时,系统性能不佳的症状很容易解释;也就是说,通常我会看到许多线程显然正在等待一个已被获取但未被另一个释放的监视器。 在这种情况下,我有很多线程在等待监视器 (0x965ad100)
C:\Users\shagy\Desktop\3RD YEAR 2ND SEMESTER\SPM\Newfolder\SPM-SMS>npm start npm ERR! path C:\Users\
我是一名优秀的程序员,十分优秀!