Reputation: 152
I just learned about RAII. From what I understand, the definition of RAII is in its name itself.For instance, (Let A be a class), consider the following function below:
void foo(){
A a;
a.init();
// Do stuff with a.
a.destroy();
}
Applaying RAII to the function above, we get:
void foo(){
// Initializing the resource completely in a consttructor.
A a;
// Do stuff with a.
// When out of scope, the destructor should be called.
}
So RAII is a good software development workflow since it reduces developer error since it takes advantage of constructor/destructor calls for resource initialization and deallocation.
Problem:
Suppose I have a class with multiple constructor, and contains data members that doesn't have a no-arg constructor to force RAII implementation. Consider the class below:
class A{
public:
A(int arg1){
int(arg1, GLOBAL_CONSTANT);
}
A(int arg1, arg2){
init(arg1, arg2);
}
void init(int arg1, int arg2){
_member = B(arg1, arg2);
}
private:
B _member; // No-arg constructor member.
};
Since B also implements the RAII methodology, it doesn't have a no-arg constructor to force the user to not use an init() method later, thus _member must be initialized in a constructor list instead of init, making the the class above erroneous.
Question:
How do you exactly deal with this? What is the industry standard on dealing with this problem, if any at all?
I see the importance of RAII and don't want to compromise. Right now, the most clean solution in my head is have a single-constructor and use a factory method to generate variations. But I don't wanna rush and first takes into account experience of others, else I'll just create a nasty code.
Upvotes: 0
Views: 174
Reputation: 9770
You must use an initializer list:
A(int arg1, arg2) : _member(arg1, arg2) {}
In C++11, you can also have constructors call each other using delegating constructors.
By the way, you should avoid using leading underscores on variable names as they are reserved if followed by a capital letter.
Upvotes: 3