I've been trying to grasp RAII, and understand that all resources should be wrapped in an object. When the object is constructed, the resource is initialized. When the object goes out of scope, the resource is deinitialized. I hope my understanding is correct. I know many of you are sticklers for RAII.
Free store memory is a resource, and thus it has to be wrapped in an object. This is a smart pointer, which ensures the memory is released when the owner smart pointer object goes out of scope. This makes a lot of extra ugly typing everywhere.
So my question is this: Can I use a bare new operator to pass a new object to a manager class that will act as it's owner? Would that acceptably follow RAII?
What I want:
class Foo
{
public:
virtual void dog() = 0;
};
class FooBazz : public Foo
{
public:
void dog(){}
};
class FooManager
{
public:
void addFoo(Foo* foo)
{
mFoos.push_back(std::move(std::unique_ptr<Foo*>(foo)));
}
private:
std::vector<std::unique_ptr<Foo>> mFoos;
};
void initStuff(FooManager& fooMgr)
{
fooMgr.addFoo(new FooBazz);
}
What I'm trying to avoid:
void initStuff(FooManager& fooMgr)
{
std::unique_ptr<Foo> foo(new FooBazz);
fooMgr.addFoo(foo);
}
My justification for the former is that you can imply that fooMgr assumes ownership of the object since it is not wrapped in a smart pointer. This is analogous to the way you can pass raw pointers as parameters into functions knowing the function is not responsible for the pointer (I've seen this done in RAII code). Also, if I as a forgetful programmer forget to assume ownership of the Foo object, my program will have bugs regardless of whether or not I wrapped it in a std::unique_ptr in initStuff(). A smart pointer would go out of scope, and the FooBazz I passed would be invalid memory later in the program. Without a smart pointer, it'd be a memory leak.
What do you guys think?