Constructor initialization and object corruption - c++

I have the following class structure, which initially threw a segfault. I have fixed the problem, but don't fully understand why the code initially through a segfault. I had a class B, a subclass of A, which,
after A initialised an object (InternalA) in the initialisation list
of the constructor, called a Run() method, which called a method on InternalA (InternalA.Start()) before calling a blocking method (io_service_.Run()), and so B's constructor never actually returned.
A separate thread would then try to access B, and call B->SendMsg(), but
all of InternalA's internal state would be corrupted. I fixed the problem by removing the blocking Run() method call from the constructor, and calling it afterwards.
Code shows me that the InternalA object does indeed get correctly initialised, but when calling b->SendMsg, InternalA is completely corrupted.
The issue that, using the new operator, the "real" address only gets assigned to the B* pointer after the constructor is returned (even though, when I check the address of b in the main thread, it is no longer null). If I instead malloced B, and subsequently called *b = B(), would it still be an issue, or would this then be architecture specific?
class B: public A
{
B(): A(arg1, arg2) { Run(); }
};
class A {
A(): InternalA()... {}
Run() {
InternalA.Start();
// Method does not terminate
io_service_.Run();
}
};
class InternalA {
InternalA(): io_service_(), map_(), id_(5) {}
void Start() {
std::cout << connections_.size() << std::endl;
}
void SendMsg() {
std::cout << connections_.size() << std::endl;
}
private:
boost::asio io_service_
std:map<X,Y> map_;
int id_;
};
int main() {
B* b = null;
std::thread t([&b] {b = new B()}); // Run() method gets called
usleep(200000);
b->SendMsg(); // All objects in InternalA are corrupted (point to invalid addresses
}

Before you can assign a value to b, that value has to be computed first. In your case, this computation (new B()) never returns, so you read uninitialized contents of the b in another thread.
Also, "a separate thread would then try to access B"? Without any checks organized to see if that "B" is actually there? You will have many hard-to-find bugs with such an approach.

Related

Understanding the construction, lifetime and destruction of objects

My question is actually two-part. A quick foreword: I am learning C++ and come from a C#/.NET background. Currently, I'm trying to understand object lifetimes and the results posted below don't make sense to me. I think it could have something to do with the creation of anonymous instances?
Question 1: Is it a good idea to dispose of all members in the destructor since it is possible that it is an "empty object" ?
Question 2: How do I prevent this? / How do I design my objects to work with this feature?
Question 3: Is this the "right" / "correct" way to do this?
Question 4: See comments in the very last bit of code
#include <stdio.h>
class A
{
public:
A()
{
printf("Constructor A\n");
}
~A()
{
printf("Destructor A\n");
}
};
class B
{
public:
B()
{
a = A();
printf("Constructor B\n");
}
~B()
{
printf("Destructor B\n");
}
private:
A a;
};
int main(int argc, char* argv[])
{
B b;
b = B();
printf("Done");
// Breakpoint
/*
Output:
Constructor A
Constructor A
Destructor A
Constructor B
Constructor A
Constructor A
Destructor A
Constructor B
Destructor B
Destructor A
*/
}
And another example that comes from a project I am currently working on.
#include <stdio.h>
class Mesh
{
public:
Mesh()
{
printf("Constructing Mesh with data %d\n", data);
}
Mesh(int d)
{
data = d;
printf("Constructing Mesh with data %d\n", data);
}
~Mesh()
{
printf("Destructing Mesh with data %d\n", data);
}
private:
int data = 0;
};
class Game
{
public:
Game()
{
printf("Game constructor\n");
}
~Game()
{
printf("Game destructor\n");
}
void init()
{
int cool_data = 3;
mesh = Mesh(cool_data);
}
private:
Mesh mesh;
};
int main(int argc, char* argv[])
{
Game game = Game();
game.init();
printf("");
// Breakpoint
/*
Output:
Constructing Mesh with data 0 <-- I assume this comes from the private member declaration in the Mesh class? So declaration means initialization?
Game constructor
Constructing Mesh with data 3 <-- Okay that's what I expected since I'm creating a new instance of the Mesh class with "3" passed in
Destructing Mesh with data 3 <-- Why is the instance we JUST created immediately being destructed?
*/
}
In your first example, we see a lot of construction and destruction of "A" objects that seems mysterious if you are not familiar with C++. Your B class has a private A variable "a". This object is default constructed when you first call the constructor to your B class. This is the very first "constructor A" print out that you see. The next print out is from the call to the A constructor here:
B()
{
a = A(); //A() calls the A constructor and returns an r-value
printf("Constructor B\n");
}
Assigning "a", an already instantiated object of class A, to the r-value returned by the call of the default constructor of class A causes you to print "Constructor A" when the r-value is created, and "Destructor A" when the r-value itself is destroyed. These behaviors can be changed by creating copy and move constructors/operators which will allow you to specify how these semantics operate. Check out this page: http://www.cprogramming.com/c++11/rvalue-references-and-move-semantics-in-c++11.html or a book (C++ 11 primer is a good one) for more info on these operations.
Following the above logic, when you assign your created B object "b" to the B class default constructor's returned rvalue in the line:
b = B();
You construct a new B object, which must
1) construct an A object
2) create an A r-value
3) destruct the A r-value
4) construct a B object
The last two print statements are simply your B object being destructed as the main exits. The B object is destructed and so is it's member, the A object. Your first question seems to be about this behavior. It looks like you're asking whether you should destruct class members manually. This is only done in C++ if your class allocates memory for its members. If, for instance, instead of creating a local A object, your constructor in B did this:
B()
{
a = new A();
printf("Constructor B\n");
}
...
private:
A* a;
Then you would have to deallocate this A* in your destructor. As long as you are not allocating new memory using the new operator or otherwise, C++ will handle all other deallocation for you.
Your questions 2 and 3 are about how to prevent/work with object construction and whether or not a given way of constructing/destructing objects is right or wrong. I would like to point you to the rule of 0/3/5. This basically deals with how many constructors you should create for a given class. This is a pretty simple explanation of the rule http://en.cppreference.com/w/cpp/language/rule_of_three, but there are many others online.
Your last question has to do with the mesh class you have and why one of your variables is being destructed. Again, this has to do with the r-value returned by the call to the constructor. Basically, when you call your mesh constructor and assign its returned value to your variable "mesh" here:
void init()
{
int cool_data = 3;
mesh = Mesh(cool_data);
}
The mesh constructor returns an r-value which is an object of class Mesh with a data value of 3; The r-value is copied into your "mesh" variable and is promptly destroyed, leaving your "mesh" variable as an exact copy of it. Again, all of these behaviors can be changed by creating appropriate constructors and operators.

Why the output is different from what I expect?

I got a simple program like this:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
class B {
protected:
int data = 0;
public:
B() { cout << "B() ctor\n";}
virtual ~B() { cout << "~B()\n"; }
virtual void method() { cout << "data in B: " << data << "\n"; }
};
class A : public B
{
int dataA = 2;
public:
A() { cout << "A() ctor\n"; }
~A() { cout << "~A()\n"; }
void method() { cout << "data in A: " << dataA << "\n"; }
};
{
B* fptrList[]{ &B{}, &A{}};
for (auto& itr : fptrList)
itr->method();
}
cin.get();
return 0;
}
Here is a result I expect:
B() ctor
B() ctor
A() ctor
data in B: 0
data in A: 2
~A()
~B()
~B()
Here is the actual result when I ran this program:
B() ctor
~B()
B() ctor
A() ctor
~A()
~B()
data in B: 0
data in B: 0
My questions are:
Why the output is different from what I expect?
How can method() be called after ~A() and ~B() get called?
Why method() of class B get called twice?
This program cannot be explained, because it exhibits undefined behavior.
Translation: it's buggy. It's taking an address of temporary objects, and then attempts to dereference them, after the temporary have been destructed.
A good C++ compiler will even tell you that the program is broken, and will refuse to participate in this disaster:
t.C: In function ‘int main()’:
t.C:26:27: error: taking address of temporary [-fpermissive]
B* fptrList[]{ &B{}, &A{}};
^
t.C:26:33: error: taking address of temporary [-fpermissive]
B* fptrList[]{ &B{}, &A{}};
^
Any output from this program is meaningless garbage.
Here is what's going on:
You initialize fptrList to addresses of temporary variables A and B
The temporary variables get destroyed right after their addresses are taken, so your code has undefined behavior.
Proper way of doing what you are trying to do it is to use operator new with smart pointers, or to make instances outside initializer.
Here is one possible fix:
{
B b;
A a;
B* fptrList[]{ &b, &a };
for (auto& itr : fptrList)
itr->method();
}
Ok, it is undefined behavior, but the question is still interesting why it is this undefined behavior.
Why are constructors/destructors are called in this order? As already established, you creates temporary objects which are created/destroyed one after each other.
Why can I call methods of already non-existent objects? Your temporary object lives at the stack and thus the memory will be freed only at the end of the main function, so you are still able to access this memory and it does not get clobbered by calls to other functions (e.g. printing to the terminal). If you would create the object with new, than delete it and than try to use it - the chances would be higher, that the system has already reclaimed this memory and you would get a segmentation error.
Why I see 2 times the method of B called? This one is funny. To call a virtual function of an object, compiler delegates the decision which method exactly should be called to a virtual table (it's address occupies the first 8 byte of such an object (at least for my compiler and 64bit)). A not that well known details about virtual methods is that during the destructor-call all virtual methods are called as if they were not virtual. But what has it to do with your code? You see its side-effect: The non-virtual behavior is ensured in the destructor by overwriting the virtual table of the current object by the virtual table of the current class. So after the destructor of B is called, the memory contains a virtual table of the class B which you can see, because B::method is called twice.
Let's track the value of the virtual table it in your program:
call of A{}: At first the superclass B-constructor is called - the (not yet fully finished) object has the virtual table of class B (this address is moved into the first 8 byte occupied by the object), than A-constructor is called - now the object has the virtual table of class A.
call of ~A(): after its execution, the destructor of A automatically calls the destructor of B. The first thing the destructor of B does is to overwrite the virtual table of the object with the virtual table of the class B.
So after the destruction the memory is still there and interpreted as an object would have the the virtual table of class B.
itr->method(); finds the virtual table of class B at the address itr points to and calls B::method().

C++ destructor with return

In C++ if we define a class destructor as:
~Foo(){
return;
}
upon calling this destructor will the object of Foo be destroyed or does
explicitly returning from the destructor mean that we don't ever want to destroy it.
I want to make it so that a certain object is destroyed only through another objects destructor i.e. only when the other object is ready to be destroyed.
Example:
class Class1{
...
Class2* myClass2;
...
};
Class1::~Class1(){
myClass2->status = FINISHED;
delete myClass2;
}
Class2::~Class2(){
if (status != FINISHED) return;
}
I searched online and couldn't seem to find an answer to my question.
I've also tried figuring it out myself by going through some code step by step with a debugger but can't get a conclusive result.
No, you can't prevent the object from being destroyed by return statement, it just means the execution of the dtor's body will end at that point. After that it still will be destroyed (including its members and bases), and the memory still will be deallocated.
You migth throw exception.
Class2::~Class2() noexcept(false) {
if (status != FINISHED) throw some_exception();
}
Class1::~Class1() {
myClass2->status = FINISHED;
try {
delete myClass2;
} catch (some_exception& e) {
// what should we do now?
}
}
Note it's a terrible idea indeed. You'd better to reconsider the design, I'm sure there must be a better one. Throwing exception won't stop the destruction of its bases and members, just make it possible to get the process result of Class2's dtor. And what could be done with it is still not clear.
~Foo(){
return;
}
means exactly the same as:
~Foo() {}
It is similar to a void function; reaching the end without a return; statement is the same as having return; at the end.
The destructor contains actions that are performed when the process of destroying a Foo has already begun. It's not possible to abort a destruction process without aborting the entire program.
[D]oes explicitly returning from the destructor mean that we don't ever want to destroy it?
No. An early return (via return; or throw ...) only means the rest of the body of the destructor is not executed. The base and members are still destroyed and their destructors still run, see [except.ctor]/3.
For an object of class type of any storage duration whose initialization or destruction is terminated by an exception, the destructor is invoked for each of the object's fully constructed subobjects...
See below for code samples of this behaviour.
I want to make it so that a certain object is destroyed only through another objects destructor i.e. only when the other object is ready to be destroyed.
It sounds like the question is rooted in the issue of ownership. Deleting the "owned" object only once the parent is destroyed in a very common idiom and achieved with one of (but not limited to);
Composition, it is an automatic member variable (i.e. "stack based")
A std::unique_ptr<> to express exclusive ownership of the dynamic object
A std::shared_ptr<> to express shared ownership of a dynamic object
Given the code example in the OP, the std::unique_ptr<> may be a suitable alternative;
class Class1 {
// ...
std::unique_ptr<Class2> myClass2;
// ...
};
Class1::~Class1() {
myClass2->status = FINISHED;
// do not delete, the deleter will run automatically
// delete myClass2;
}
Class2::~Class2() {
//if (status != FINISHED)
// return;
// We are finished, we are being deleted.
}
I note the if condition check in the example code. It hints at the state being tied to the ownership and lifetime. They are not all the same thing; sure, you can tie the object reaching a certain state to it's "logical" lifetime (i.e. run some cleanup code), but I would avoid the direct link to the ownership of the object. It may be a better idea to reconsider some of the semantics involved here, or allow the "natural" construction and destruction to dictate the object begin and end states.
Side note; if you have to check for some state in the destructor (or assert some end condition), one alternative to the throw is to call std::terminate (with some logging) if that condition is not met. This approach is similar to the standard behavior and result when an exception is thrown when unwinding the stack as a result of an already thrown exception. This is also the standard behavior when a std::thread exits with an unhandled exception.
[D]oes explicitly returning from the destructor mean that we don't ever want to destroy it?
No (see above). The following code demonstrates this behaviour; linked here and a dynamic version. The noexcept(false) is needed to avoid std::terminate() being called.
#include <iostream>
using namespace std;
struct NoisyBase {
NoisyBase() { cout << __func__ << endl; }
~NoisyBase() { cout << __func__ << endl; }
NoisyBase(NoisyBase const&) { cout << __func__ << endl; }
NoisyBase& operator=(NoisyBase const&) { cout << __func__ << endl; return *this; }
};
struct NoisyMember {
NoisyMember() { cout << __func__ << endl; }
~NoisyMember() { cout << __func__ << endl; }
NoisyMember(NoisyMember const&) { cout << __func__ << endl; }
NoisyMember& operator=(NoisyMember const&) { cout << __func__ << endl; return *this; }
};
struct Thrower : NoisyBase {
Thrower() { cout << __func__ << std::endl; }
~Thrower () noexcept(false) {
cout << "before throw" << endl;
throw 42;
cout << "after throw" << endl;
}
NoisyMember m_;
};
struct Returner : NoisyBase {
Returner() { cout << __func__ << std::endl; }
~Returner () noexcept(false) {
cout << "before return" << endl;
return;
cout << "after return" << endl;
}
NoisyMember m_;
};
int main()
{
try {
Thrower t;
}
catch (int& e) {
cout << "catch... " << e << endl;
}
{
Returner r;
}
}
Has the following output;
NoisyBase
NoisyMember
Thrower
before throw
~NoisyMember
~NoisyBase
catch... 42
NoisyBase
NoisyMember
Returner
before return
~NoisyMember
~NoisyBase
According to the C++ Standard (12.4 Destructors)
8 After executing the body of the destructor and destroying any
automatic objects allocated within the body, a destructor for class X
calls the destructors for X’s direct non-variant non-static data
members, the destructors for X’s direct base classes and, if X is the
type of the most derived class (12.6.2), its destructor calls the
destructors for X’s virtual base classes. All destructors are called
as if they were referenced with a qualified name, that is, ignoring
any possible virtual overriding destructors in more derived classes.
Bases and members are destroyed in the reverse order of the completion
of their constructor (see 12.6.2). A return statement (6.6.3) in a
destructor might not directly return to the caller; before
transferring control to the caller, the destructors for the members
and bases are called. Destructors for elements of an array are called
in reverse order of their construction (see 12.6).
So a returning statement does not prevent the object for which the destructor is called to be destroyed.
does explicitly returning from the destructor mean that we don't ever want to destroy it.
No.
The destructor is a function so you can use the return keyword inside of it but that won't prevent the destruction of the object, once you are inside the destructor you are already destroying your object so any logic that wants to prevent that will have to occur before.
For some reason i intuitively think your design problem can be solved with a shared_ptr and maybe a custom deleter, but that would require more info on the said problem.
All stack-based objects inside will get destructed, no matter how soon you return from the destructor. If you miss to delete dynamically allocated objects, then there would be intentional memory leak.
This is the whole idea how move-constructors would work. The move CTOR would simply take original object's memory. The destructor of original object simply wont/cant call delete.
No. return just means exit the method, it doesn't stop the destruction of the object.
Also, why would you want to? If the object is allocated on the stack and you somehow managed to stop destruction then the object would live on a reclaimed part of the stack that will probably be overwritten by the next function call, which may write all over your objects memory and create undefined behavior.
Likewise, if the object is allocated on the heap and you managed to prevent destruction you'd have a memory leak as the code calling delete would assume that it didn't need to hold on to a pointer to the object whilst it's actually still there and taking up memory that nobody is referencing.
Of course not. Explicit call of 'return' ist 100% equivalent to implicit returning after execution of the destructor.
You can make a new method to make the object "commit suicide" and keep the destructor empty, so something like this will do the job you would like to do:
Class1::~Class1()
{
myClass2->status = FINISHED;
myClass2->DeleteMe();
}
void Class2::DeleteMe()
{
if (status == FINISHED)
{
delete this;
}
}
Class2::~Class2()
{
}
So, as all the others pointed out, return is not a solution.
The first thing I would add is that you shouldn't usually worry about this. Unless your professor explicitly asked.
It would be very odd if you could't trust the external class to only delete your class at the right time, and I figure no one else is seeing it.
If the pointer is passed around, the pointer would very probably be shared_ptr/weak_ptr, and let it destroy your class at the right moment.
But, hey, it's good to wonder how we would solve an odd problem if it ever arose, if we learn something (and don't waste time while on a deadline!)
So what for a solution? If you can at least trust the destructor of Class1 not to destroy your object too early, then you can just declare the destructor of Class2 as private, and then declare the destructor of Class1 as friend of Class2, like this:
class Class2;
class Class1 {
Class2* myClass2;
public:
~Class1();
};
class Class2 {
private:
~Class2();
friend Class1::~Class1();
};
Class1::~Class1() {
delete myClass2;
}
Class2::~Class2() {
}
As a bonus, you don't need the 'status' flag; which is good -if someone wanted this bad to screw with you, why wouldn't set the status flag to FINISHED anywhere else, and then call delete?
This way, you have actual guarantee that the object can be destroyed nowhere else than in the destructor of Class1.
Of course, the destructor of Class1 gets access to all private members of Class2. It might not matter -after all, Class2 is about to be destroyed anyway! But if it does, we can conjure even more convoluted ways to work around it; why not. For instance:
class Class2;
class Class1 {
private:
int status;
Class2* myClass2;
public:
~Class1();
};
class Class2Hidden {
private:
//Class2 private members
protected:
~Class2Hidden();
public:
//Class2 public members
};
class Class2 : public Class2Hidden {
protected:
~Class2();
friend Class1::~Class1();
};
Class1::~Class1() {
delete myClass2;
}
Class2Hidden::~Class2Hidden() {
}
Class2::~Class2() {
}
This way the public members will still be available in the derived class, but the private members will actually be private. ~Class1 will only get access to the private and protected members of Class2, and the protected members of Class2Hidden; which in this case is only the destructors.
If you need to keep a protected member of Class2 protected from the destructor of Class1... there are ways, but it really depends on what you are doing.
Good luck!
For this case you could use a class-specific overload of the delete operator.
So for you Class2 you could something like this
class Class2
{
static void operator delete(void* ptr, std::size_t sz)
{
std::cout << "custom delete for size " << sz << '\n';
if(finished)
::operator delete(ptr);
}
bool Finished;
}
Then if you set the finished to true before the delete, the actual deletion will be called.
Note that i haven't tested it, i just modified the code that i've found here
http://en.cppreference.com/w/cpp/memory/new/operator_delete
Class1::~Class1()
{
class2->Finished = true;
delete class2;
}

Destroying an object with ongoing function call

Assume I have class A with resource B. Class A has a function that does not acquire a mutex lock before I want to destroy it. I call boost::shared_ptr::reset() to destroy instance of class A. Is resource B guaranteed to be destroyed at that point?
class Resource{
public:
Resource(){ }
~Resource(){ free(); }
void init() {}
void free() {}
};
class A{
public:
A(){ B.init(); }
~A(){}
void functionC(){
boost::lock_guard<boost::mutex> lock(Mutex);
// Stuck forever
boost::lock_guard<boost::mutex> lock2(Mutex);
}
private:
boost::mutex Mutex;
Resource B;
};
main(){
boost::shared_ptr<A> pointer(new A());
// Do a function call that gets stuck but allows main thread to continue
boost::thread t(boost::bind(&A::functionC, *pointer));
pointer.reset();
// Loop forever
while(1);
}
To be specific, I want function B::free() to be called at the point in which I call pointer.reset(). Is this code guaranteed to do that, or do I have to explicitly call it somewhere? Obviously I don't want to be as explicit as
pointer->freeB();
pointer.reset();
In your scenario, B is a member of A. It will get destroyed (and free() will be called) when A gets destroyed. No need for an explicit call.
However in your code, there's no guarantee that your pointer.reset() the allocated A object gets destroyed: it only gets destroyed if pointer was the only shared_ptr pointing to this object, i.e. no copy of the pointer was made since its creation (there 's no evidence of that here, but to be checked in your real code).
By the way, there's a t.join() missing in your code.

Appropriate use for boost::shared_ptr?

A question about boost::shared_ptr here:
I have 3 Classes.
A is some kind of Main class which is responsible to manage everything.
B is a class which just has functions to do some work.
Dispatcher is just a class which wraps around a seperate thread, which gets the work from Instaces of Bdone in this thread.
So it is kinda working like this: A has an instance of Dispatcher. Now on occassion A generates an instance of B and passes it to the dispatcher.
The important part is, that B needs to call A::callback() when it's done. This is why B gets a reference to A in it's constructor ( see code below )
A.hpp
class A : public boost::enable_shared_from_this<A>
{
public:
A();
void sendB();
void callback();
private:
Dispatcher m_Dispatcher;
};
B.hpp
class B
{
public:
B(boost::shared_ptr<A> ptr);
boost::shared_ptr<A> m_PointerToA;
/* Some other functions */
};
Dispatcher.hpp
class Dispatcher
{
public:
void run();
void dispatch(boost::shared_ptr<B> b);
private:
void doWork();
boost::thread m_Thread;
};
A.cpp
A::A()
{
m_Dispatcher.run();
}
void A::sendB()
{
boost::shared_ptr ptr_B;
ptr_B.reset(new B(this->shared_from_this);
m_Dispatcher.dispatch(ptr_B);
}
B.cpp
B::B(boost::shared_ptr<A> ptr) :
: m_PointerToA(ptr)
{
}
main_example.cpp
int main()
{
A instanceA;
while(true)
{
instanceA.sendB();
/* Do some other stuff */
}
return 0;
}
So my question is:
Is it reasonable to use boost::shared_ptr for this purpose?
I am not sure if the shared_ptr is the right thing to go here. My problem is, that I don't know what happens exactly when I call the constructor from B and pass it the this pointer. Now according to shared_ptr I would assume that m_PointerToA takes ownership of A. But this would mean that when the work in the Dispatcher is done and my instance of B gets deleted it would also delete the reference to m_PointerToA which would actually mean it kills the object itself despite the fact there is an actual instance of A in the main loop.
Update:
Added some code and updated question itself to make it more clear.
There's nothing particular wrong with this design. However I would prefer to instead use boost::function<> & boost::bind. It gives you way better flexibility for the callback and doesn't tie B as tightly to A. Of course you still have to be vary of the usual threading caveats.
Yes, it is okay to just copy/assign a shared_ptr, it will only increase the reference count.
In your example, shared_from_this() will create a (here: temporary) shared_ptr from the weak_ptr that is hold by this (ref count 1), so when you assign/copy-construct m_PointerToA, the reference count will increase temporarily to 2 before the ctor returns and the temporary object will be destroyed, decreasing the reference count to 1 again (the shared_ptr is "aware" of the one instance in your B object).
So, yes, if B is deleted, it will destroy A in this case (as the reference count drops to 0).
Your concern
This would mean if my Instance of B is deleted, it would also delete m_PointerToA which would also kill my instance of A . Of course my original instance of A is held elsewhere.
only shows that if you plan/need/intend to keep a pointer to the instance of A for further usage, you should do so with a shared_ptr as well instead of a raw pointer. If you have control of A's interface, the easiest way would be a named constructor like this:
class A : public boost::enable_shared_from_this<A> {
public:
static boost::shared_ptr<A> create();
void initClassB();
// ....
private:
A();
A( const A & other );
A& operator=( const A & rhs );
};
boost::shared_ptr<A> A::create() {
return boost::shared_ptr<A>( new A() );
}
Then, even if your instance of B is deleted, the instance of A will still survive because the reference count of the shared_ptr is still (at least) 1.