2017-11-25 143 views
3

爲以下包裝類跟上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)是否會被銷燬。 它似乎不是從上面,但我應該期待這一點?上述解決方案是否存在缺陷?

+0

代碼雖然我必須承認我不太明白這個練習的重點,但我不明白這個問題應該是一個解決方案在...上。 –

+0

** rvalue destructor **是什麼意思? –

+0

我的意思是'who_is_this(myobj_wrapper(「Alice」)。who);' –

回答

1

我不知道,但這裏是我的觀點:

who_is_this(myobj_wrapper("Alice").who); 

這將創建一個包裝對象,將採取字符串文字作爲參數。然後,一個myobj實例將被動態創建,並移交給一個唯一的指針。通過這個實例,我們得到它的數據(字符串),並從包裝類指向它的傳統指針。所以,現在who指向me,即愛麗絲。

我們通過who(這是一個指針):

void who_is_this(std::string *who) 

這意味着該函數的參數who副本,而是指向原始數據。

所以現在整個問題是當包裝器對象超出範圍時(因此它的數據成員(唯一指針)也將超出範圍,這意味着已動態創建的myobj實例將被垃圾收集,這又意味着me將走出去的範圍太,等會who

包裝對象將走出去的範圍,後who_is_this()得到執行,這意味着你的代碼是OK。

+0

「的動態分配對象_包含對象將在** who_is_this()被執行後超出範圍**,這意味着您的代碼OK_「很酷,謝謝你的回答! –

+1

Thx。我想有人可能會添加關於陷阱的評論。我猜沒有任何。具體的例子是[這裏](https://github.com/boennecd/dynamichazard/blob/master/src/problem_data.h),我使用Armadillo庫。請參閱'map_res'類,例如'lp_map'方法。有時需要新的'arma :: vec',而在其他時候則不需要創建新的對象。 (忽視類之上的評論 - 這是錯誤的)。 –