I am new to boost library and trying boost::scoped_ptr
, it states this smart pointer cannot be copied or moved. But I was playing with some code and found an issue. I was able to create new instance of scoped_ptr
and initialize it with existing valid scoped_ptr
. So if one of the scoped_ptr
's scope is over and deallocates the memory , other scoped_ptr still thinks its valid pointer and tries to access. It gave me error at runtime.
I am working on boost library version 1.66, with cygwin g++ compiler and using std=c++03 option while compiling.
#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;
}
So below is the snapshot of code run after compiling fine...
-> g++ -std=c++03 -Wall scoped_ptr.cpp
-> ./a.exe
9
25769804960
9
25769804960
-2144292696
25769804960
12
25769879920
Aborted (core dumped)
At end of execution is shows core dump, it incorrectly displayed -2144292696
in above run.
Also I checked boost::scoped_ptr
was able to assign it to pointer
int * p = pi.get()
statement compiles fine (should this work?)
Is above operation initializing scoped_pt
r with other scoped_ptr
valid?