Is the following wrapper class an "OK" way of keeping an intermediate object with std::unique_ptr to access the me member without copying me?
Here is the example
#include <iostream>
#include <memory>
/* myobj from another library */
class myobj {
public:
std::string me; /* actual member of interest is larger and more
complicated. Don't want to copy of me or myobj */
/* more members in actual class */
myobj(std::string i_am) {
/* more stuff happens in constructor */
me = i_am;
}
~myobj(){
std::cout << me << ": Goodbye" << std::endl;
}
};
/* A function in another library */
void who_is_this(std::string *who){
std::cout << "This is " << *who << std::endl;
}
/* wrapper which I define */
class myobj_wrapper {
using obj_ptr = std::unique_ptr<myobj>;
obj_ptr ptr;
public:
std::string *who;
myobj_wrapper(std::string i_am):
ptr(new myobj(i_am)), who(&ptr.get()->me) {}
myobj_wrapper(myobj &the_obj): who(&the_obj.me) { }
};
int main()
{
{
myobj bob("Bob");
who_is_this(myobj_wrapper(bob).who);
}
who_is_this(myobj_wrapper("Alice").who);
return 0;
}
The resulting program yields
This is Bob
Bob: Goodbye
This is Alice
Alice: Goodbye
I define myobj_wrapper for multiple object to get the who pointer. What I am unsure of whether the object of interest (std::string in the above) will get destroyed before it is evaluated in the who_is_this function. It does not seem to from the above but should I expect this? Are there pitfalls with the above solution?
I am not sure, but here is my point of view:
who_is_this(myobj_wrapper("Alice").who);
This will create a wrapper object, that will take the string literal as its argument. Then, a myobj instance will be dynamically created, and handed over to a unique pointer. Via that instance, we get its data (the string), and make a traditional pointer from the wrapper class point to it. So, now who is pointing to me, i.e. Alice.
We pass who (which is a pointer) to:
void who_is_this(std::string *who)
which means that the function's parameter who is not a copy, but points to the original data.
So now the whole question is when the wrapper object will go out of scope (thus its data member (the unique pointer) will go out of scope too, meaning that the myobj instance which had been dynamically created will be garbage collected, which in turns means that me will go out of scope too, and so will who.
The wrapper object will go out of scope, after who_is_this() gets executed, which means that your code is OK.
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