|
Boost Users : |
From: Evan Drumwright (edrumwri_at_[hidden])
Date: 2006-06-28 09:28:17
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 <boost/shared_ptr.hpp>
int main()
{
std::vector<boost::shared_ptr<int> > 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<const int*>(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<int*>(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
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net