这是C++ Primer第18章的练习:
void exercise(int *b, int *e)
{
vector<int> v(b, e);
int *p = new int[v.size()];
ifstream in("ints");
// exception occurs here
}
Run Code Online (Sandbox Code Playgroud)
上面的代码会导致内存泄漏,因为我们直接管理的内存(即p)在发生异常时不会自动释放.
练习18.3:
如果抛出异常,有两种方法可以使前面的代码正常工作.描述它们并实施它们.
我知道我们可以使用智能指针来避免这个陷阱:
void exercise(int *b, int *e)
{
vector<int> v(b, e);
unique_ptr<int[]> p(new int[v.size()]);
ifstream in("ints");
// exception occurs here
}
Run Code Online (Sandbox Code Playgroud)
要么:
void exercise(int *b, int *e)
{
vector<int> v(b, e);
shared_ptr<int> p(new int[v.size()], [](int *p){ delete[] p; });
ifstream in("ints");
// exception occurs here
}
Run Code Online (Sandbox Code Playgroud)
我不确定这些是不是TWO.毕竟,它们实际上是相同的.所以我想到了另一种方式:
void exercise(int *b, int …Run Code Online (Sandbox Code Playgroud) 这是一个例子:
#include <string>
#include <algorithm>
#include <memory>
using std::string;
int main()
{
string str = "This is a string";
// ok: needn't using declaration, ADL works
auto it = find(str.begin(), str.end(), 'i');
// error: why ADL doesn't work?
std::shared_ptr<string> sp = make_shared<string>(str);
}
Run Code Online (Sandbox Code Playgroud)
当我试图编译这个程序时,编译器抱怨:
error: no template named 'make_shared'; did you mean 'std::make_shared'?
std::shared_ptr<string> sp = make_shared<string>(str); // error...
^~~~~~~~~~~
std::make_shared
Run Code Online (Sandbox Code Playgroud)
我猜第一个函数find不需要using声明,因为依赖于参数的lookup(ADL):编译器会搜索名称空间string(即std)的定义find.但对于第二个函数make_shared,它似乎ADL不起作用:我必须使用std::make_shared或 …