13.3. Swap

//Exercises Section 13.3
//Exercise 13.29: Explain why the calls to swap inside swap(HasPtr&,
//HasPtr&) do not cause a recursion loop.
//For the swap inside function feed the library swap.

//Exercise 13.30: Write and test a swap function for your valuelike version of
//HasPtr.Give your swap a print statement that notes when it is executed.
/*class HasPtr {
public:
	friend void swap(HasPtr &, HasPtr &);
	HasPtr(const string &s = string()) : ps(new string(s)), i(0) { }
	HasPtr(const HasPtr &hp) : ps(new string(*hp.ps)), i(hp.i) { }
	HasPtr &operator=(HasPtr &hp) {
		swap(*this, hp);
		return *this;
	}

	string *ps;
	int i;
};

inline void swap(HasPtr &lhs, HasPtr &rhs) {
	using std::swap;
	swap(lhs.ps, rhs.ps);
	swap(lhs.i, rhs.i);
	cout << "swap(HasPtr &lhs, HasPtr &rhs)\n";
}

int main() {
	HasPtr h("hello "), p("world!");
	cout << *h.ps << *p.ps << endl;
	swap(h, p);
	cout << *h.ps << *p.ps << endl;
	return 0;
}*/

//Exercise 13.31: Give your class a < operator and define a vector of
//HasPtrs.Give that vector some elements and then sort the vector.
//Note when swap is called.
/*class HasPtr {
friend void swap(HasPtr &, HasPtr &);
public:	
	HasPtr(const string &s = string()) : ps(new string(s)), i(0) { }
	HasPtr(const HasPtr &hp) : ps(new string(*hp.ps)), i(hp.i) { }
	HasPtr &operator=(HasPtr &hp) {
		swap(*this, hp);
		return *this;
	}
	void show() const { cout << *ps << endl; }
	bool operator<(const HasPtr &hp) const {
		return *ps < *hp.ps;
	}

	string *ps;
	int i;
};

inline void swap(HasPtr &lhs, HasPtr &rhs) {
	using std::swap;
	swap(lhs.ps, rhs.ps);
	swap(lhs.i, rhs.i);
	cout << "call swap(HasPtr &lhs, HasPtr &rhs)\n";
}

int main() {
	HasPtr a("b"), b("c"), c("a");
	vector<HasPtr> vec{ a, b, c };
	sort(vec.begin(), vec.end());
	for (auto const &elem : vec) elem.show();
	return 0;
}*/

//Exercise 13.32: Would the pointerlike version of HasPtr benefit from
//defining a swap function ? If so, what is the benefit ? If not, why not?
//No, it needn't to avoid memory allcoation.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值