Here is my code of what I am doing :
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
int main()
{
vector<int> ar = {1};
shared_ptr<int> sp(&ar[0]);
cout<<*sp<<endl; // ---- [1]
ar[0] = 10;
cout<<*sp<<endl; // ---- [2]
ar.clear();
cout<<*sp<<endl; // ---- [3]
return 0;
}
The output is coming to be :
1
10
10
Instead of cout
at [3]
I think, there should be any error at runtime, since the the object to be accessed is already deleted. How it is printing 10
in [3]
? Or should I use any g++
flag, I am just using g++ -std=c++14 a1.cpp && ./a.out
EDIT: On running on Coliru I found out that clang++
is giving
`*** glibc detected *** ./a.out: double free or corruption (fasttop): 0x0000000002138010 ***`
But g++
is not Coliru.
You're pretty much bypassing anything that would guarantee a run-time error when you try to access outside the current bounds of the vector.
If you want the bounds checked, you might consider something like this instead:
A
shared_ptr
is for shared ownership of an object, so the object will be deleted only when there's nothing left to own it. By contrast, astd::vector
assumes sole ownership of all the objects it contains, so trying to refer to one of them with ashared_ptr
leads only to problems.On the other hand, the fact that with gcc this manages to exit without a (visible) sign of the problem doesn't technically qualify as a bug in the compiler. At the end of the scope, the
shared_ptr
and thestd::vector
will both attempt to free theint
to which theshared_ptr
refers--but there's no requirement that doing so leads to an error message (officially that's a quality of implementation issue, though I'd certainly agree that showing the message is better than not).