Is the following wrapper class an "OK" way of keeping an intermediate object withstd::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 << ": Good bye" << 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: Good bye
This is Alice
Alice: Good bye
I define myobj_wrapper
for multiple object to get the who
pointer. What I am unsure of is whether the object of interest (std::string
in the above) will get destroyed before is evaluated in the who_is_this
function. It does not seem to from the above but should I expect this?
Aucun commentaire:
Enregistrer un commentaire