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.
The shared_ptr type is a smart pointer in the C++ standard library that is designed for scenarios in which more than one owner might have to manage the lifetime of the object in memory.
Use unique_ptr when you want to have single ownership(Exclusive) of the resource. Only one unique_ptr can point to one resource. Since there can be one unique_ptr for single resource its not possible to copy one unique_ptr to another. A shared_ptr is a container for raw pointers.
Reason Passing a smart pointer transfers or shares ownership and should only be used when ownership semantics are intended (see R. 30). Passing by smart pointer restricts the use of a function to callers that use smart pointers. Passing a shared smart pointer (e.g., std::shared_ptr) implies a run-time cost.
As shown in the example, a smart pointer is a class template that you declare on the stack, and initialize by using a raw pointer that points to a heap-allocated object.
One further possibility is to create the object as a static_ptr for ease of memory management, but just pass the raw pointer to the other private methods:
void privateMethod1(Foo *fooObj);
void showSomethingOnTheScreen() {
scoped_ptr<Foo> fooObj(new Foo);
privateMethod1(fooObj.get());
};
I would use scoped_ptr inside showSomethingOnTheScreen, but pass a raw pointer (or reference) to privateMethod1, e.g.
scoped_ptr<Foo> fooObj(new Foo);
privateMethod1(fooObj.get());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With