爲以下包裝類跟上std::unique_ptr
中間對象來訪問me
成員而不復制me
的「OK」的方式?當被稱爲右值析構函數/這是正確的
下面是示例
#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;
}
所得程序收率
This is Bob
Bob: Goodbye
This is Alice
Alice: Goodbye
我定義myobj_wrapper
多個對象以獲得who
指針。在who_is_this
函數中評估之前,我不確定感興趣的對象(上面的std::string
)是否會被銷燬。 它似乎不是從上面,但我應該期待這一點?上述解決方案是否存在缺陷?
代碼雖然我必須承認我不太明白這個練習的重點,但我不明白這個問題應該是一個解決方案在...上。 –
** rvalue destructor **是什麼意思? –
我的意思是'who_is_this(myobj_wrapper(「Alice」)。who);' –