2012-02-15 5 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 "; } '?このコピーは、すべて省略されていることが保証されています。 –

+0

+1とジェームス、しかし、 'それ以外のものは避けてください。 –

+0

私のコードはそれよりずっと複雑ですが、ポインタの制約は回避できません。 – klefevre

答えて

3

:返品のタイプを変更することなく:

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

(James McNellisが述べたように値で返さなければ、_want_動的に割り当てられたメモリと仮定します) –

+0

いい方法ですが、戻り値の型を変更せずにそれを行う方法はありますか? (std :: string *)?私はdynamic_castについて考えていましたが、正しく動作するようにはできません。 – klefevre

+0

答えが更新されました。 –

0

これはどう:

#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() 
{ 
    std::string * ret = new std::string("foo"); 
    // do stuff with ret 
    return ret; 
} 
+1

もちろん、このコードは動作します。始めに、私はこれをしましたが、私はvarでいくつかのことをしなければなりません。しかし、私はチェックするために多くの例外があり、私は各スローの前に私のvarを削除する必要があります。だから、私はローカル変数を作成し、テストの後にポインタを返すことにしました。 – klefevre

+1

私の答えを完成させるために、スマートポインタは投げても削除されることが保証されています。 –

関連する問題