I have a class that creates an object inside one public method. The object is private and not visible to the users of the class. This method then calls other private methods inside the same class and pass the created object as a parameter:
class Foo { ... }; class A { private: typedef scoped_ptr<Foo> FooPtr; void privateMethod1(FooPtr fooObj); public: void showSomethingOnTheScreen() { FooPtr fooObj(new Foo); privateMethod1(fooObj); }; };
I believe the correct smart pointer in this case would be a scoped_ptr, however, I can’t do this because scoped_ptr makes the class non copyable if used that way, so should I make the methods like this:
void privateMethod1(FooPtr& fooObj);
privateMethod1 doesn’t store the object, neither keeps references of it. Just retrieves data from the class Foo.
The correct way would probably be not using a smart pointer at all and allocating the object in the stack, but that’s not possible because it uses a library that doesn’t allow objects on the stack, they must be on the Heap.
After all, I’m still confused about the real usage of scoped_ptr.
Use here simple std::auto_ptr as you can’t create objects on the stack. And it is better to your private function just simply accept raw pointer.
Real usage is that you don’t have to catch all possible exceptions and do manual delete.
In fact if your object is doesn’t modify object and your API return object for sure you’d better to use
and pass the object there as