我不熟悉Boost库,尝试使用boost::scoped_ptr
,它指出该智能指针无法复制或移动。但是我在玩一些代码,发现了一个问题。我能够创建scoped_ptr
的新实例,并使用现有有效的scoped_ptr
对其进行初始化。因此,如果scoped_ptr
的作用域之一已结束并释放了内存,则其他scoped_ptr仍会认为其有效指针并尝试访问。它在运行时给我错误。
我正在使用cygwin g ++编译器开发boost库版本1.66,并在编译时使用std = c ++ 03选项。
#include<boost/scoped_ptr.hpp>
#include<iostream>
using namespace std;
int main(){
boost::scoped_ptr<int> pi(new int(9));
cout << *pi << endl;
cout << uintptr_t(pi.get()) << endl;
boost::scoped_ptr<int> ppi(pi.get()); // initialized with same memory pointed by pi.
cout << *ppi << endl; // so ownership of same memory is with pi.
cout << uintptr_t(ppi.get()) << endl; // as well as with ppi.
pi.reset(new int(12)); //its previous memory location pointing to 9 is deallocated.
cout << *ppi << endl; // throws garbage value..
cout << uintptr_t(ppi.get()) << endl; // shows same memory location it had previous memory shown by pi.
cout << *pi << endl;
cout << uintptr_t(pi.get()) << endl;
return 0;
}
因此,下面是编译良好后运行的代码的快照...
-> g++ -std=c++03 -Wall scoped_ptr.cpp
-> ./a.exe
9
25769804960
9
25769804960
-2144292696
25769804960
12
25769879920
Aborted (core dumped)
执行结束时显示核心转储,在以上运行中错误地显示了-2144292696
。
我还检查了boost::scoped_ptr
能否将其分配给指针int * p = pi.get()
语句可以很好地编译(这可以吗?)
上述操作用其他scoped_pt
初始化scoped_ptr
r是否有效?