Hi all,
I am having trouble with pointer ownership as a result of the const_cast
operator. In particular, for the code below, when a const_cast is used to
create a const int pointer, the use count for x does not increase. The
result of this is that when x.pop_back() is called, y is no longer valid
(though the use count for y remains 1).
The documentation for shared_ptr does not help here. Any suggestions?
Thanks,
Evan
#include <vector>
#include <iostream>
#include
int main()
{
std::vector x;
x.push_back(boost::shared_ptr<int>(new int));
*x.front() = 4;
std::cout << "use count: " << x.front().use_count() << std::endl;
boost::shared_ptr<const int> y(const_cast(x.front().get()));
std::cout << "use count: " << x.front().use_count() << std::endl;
std::cout << "use count: " << y.use_count() << std::endl;
boost::shared_ptr<int> z(const_cast(y.get()));
std::cout << "use count: " << z.use_count() << std::endl;
std::cout << "use count: " << y.use_count() << std::endl;
x.pop_back();
std::cout << *y << std::endl;
}
Output:
use count: 1
use count: 1
use count: 1
use count: 1
use count: 1
0