2012-02-15 19 views
0

是否可以在C++中動態分配一個臨時變量?
我想要做這樣的事情:是否可以在C++中動態分配一個臨時變量?

#include <iostream> 
#include <string> 

std::string* foo() 
{ 
    std::string ret("foo"); 
    return new std::string(ret); 
} 

int main() 
{ 
    std::string *str = foo(); 
    std::cout << *str << std::endl;                           
    return 0; 
} 

此代碼的工作,但問題是我爲了回擊一個指針來創建另一個字符串。有沒有辦法將我的臨時/本地變量放入堆中而不重新創建其他對象?
這裏是我會怎麼做一個例證:

std::string* foo() 
{ 
    std::string ret("foo"); 
    return new ret; // This code doesn't work, it is just an illustration 
} 
+5

'std :: string foo(){return「foo」; }'?該副本都保證不會被刪除。 – 2012-02-15 02:48:32

+0

+1給詹姆斯,但是要避免'除了'外,對於我們這些非英語母語人士來說,這是令人困惑的。 – 2012-02-15 02:55:33

+0

我的代碼比這複雜得多,指針約束是不可避免的。 – klefevre 2012-02-15 02:59:44

回答

3

嗯,是有,這就是所謂的智能指針:

#include <memory> 
std::unique_ptr<std::string> foo() 
{ 
    return std::unique_ptr<std::string>("foo"); 
} 

// Use like this: 
using namespace std; 
auto s = foo();  // unique_ptr<string> instead of auto if you have an old standard. 
cout << *s << endl; // the content pointed to by 's' will be destroyed automatically 
        // when you stop using it 

編輯:無需更改退貨類型:

std::string* foo() 
{ 
    auto s = std::unique_ptr<std::string>("foo"); 
    // do a lot of stuff that may throw 

    return s.release(); // decorellate the string object and the smart pointer, return a pointer 
         // to the string 
} 
+1

(我假設你_want_動態分配內存,如果你沒有按James McNellis提到的那樣返回值) – 2012-02-15 02:56:14

+0

這是一個很好的方法,但是有沒有辦法在不改變返回類型的情況下做到這一點? (std :: string *)?我正在考慮dynamic_cast,但我無法讓它正常工作。 – klefevre 2012-02-15 03:02:20

+0

有,讓我更新答案。 – 2012-02-15 03:05:11

0

如何:

std::string* foo() 
{ 
    std::string * ret = new std::string("foo"); 
    // do stuff with ret 
    return ret; 
} 
+1

當然,這段代碼的作品。在開始時,我已經完成了這個,但我必須用我的變種做一些事情。但我有很多例外檢查,我必須在每次拋出前刪除我的var。所以我決定創建一個局部變量,然後在測試之後返回一個指針。 – klefevre 2012-02-15 02:54:55

+1

爲了完成我的回答,即使拋出智能指針也保證被刪除。 – 2012-02-15 03:03:44

相關問題