Hi,
(Using gcc 4.0.2, boost 1.33.1, linux)
I've got a program which causes segfaults using shared_ptr. I've reduced
the program as far as I can to show the fault without any extra fluff. It
looks as if an object pointed to by a shared_ptr is being deleted more than
once.
What I'm trying to do is to have an instance of Memory 'know' about
an instance of Foo. This is currently being done with a shared_ptr.
It appears that I'm misusing shared_ptr in the assignment, but I'm
unsure as to what the right way is. Alternatively, I probably could
use a reference instead of a shared_ptr, but I'm not sure if the
Foo instance will always exist.
Thanks in anticipation.
#include <cstdlib>
#include <iostream>
#include <string>
#include
class Memory;
typedef boost::shared_ptr<Memory> MemoryPtr;
class Foo;
typedef boost::shared_ptr<Foo> FooPtr;
class Memory
{
public:
Memory () : fp () {
std::cout << "Constructed Memory" << std::endl;
};
virtual ~Memory () {
std::cout << "Destructing Memory" << std::endl;
std::cout << "fp.use_count=" << fp.use_count () << std::endl;
};
void remember1 (FooPtr f) {
std::cout << "Remembering" << std::endl;
fp = f;
};
private:
FooPtr fp;
};
class Foo
{
public:
Foo (const std::string& name_) : name (name_) {
std::cout << "Constructed Foo '" << name << "'" << std::endl;
};
virtual ~Foo () {
std::cout << "Destructing Foo '" << name << "'" << std::endl;
};
void test (MemoryPtr m) {
m -> remember1 (FooPtr (this));
}
private:
const std::string name;
};
int main ()
{
{
FooPtr f1 (new Foo ("first"));
MemoryPtr m1 (new Memory ());
f1 -> test (m1);
}
return EXIT_SUCCESS;
}