0

I created a program like below

void Encode(shared_ptr<string>str)
{
    shared_ptr<string> n(new string());
        //I am creating the string pointed by n here by analyzing the string pointed by str 
    cout<<endl;
    cout<<str.get()<<" Func "<<str.use_count()<<" "<<n.get()<<" "<<n.use_count()<<endl;
    str=n;
    cout<<str.get()<<" Func "<<str.use_count()<<" "<<n.get()<<" "<<n.use_count()<<endl;
}

int main ()
{
    string s("aaabbbccd");
    shared_ptr<string> str(new string(s));
    Print(str);
    cout<<endl;
    cout<<str.get()<<"  Main "<<str.use_count()<<" "<<endl;
    Encode(str);
    cout<<str.get()<<" Main "<<str.use_count()<<" "<<endl;
    cout<<endl;
    Print(str);
    _getch();
    return 0;
}

Since i am encoding the string ,so i do not want the original string after I encode, I tried by writing the line str=n to do it thinking that this would make str point to the new string which I can use in my main program, but it is not correct as i am getting the original string only as output ,not the modified one.

I even checked using .get() function and it seems that it is pointing to the original string only.

Can anyone explain me why it is so and how can i make str to point to the new string?

4

1 に答える 1

1

関数には、共有ポインターのコピーEncodeが渡されます。そして、そのコピーを変更しているだけです。メインのものではありません。

void Encode(shared_ptr<string>str)

代わりに参照渡しでポインターを渡す必要があります。次に、メインで同じものを参照します。shared_ptr

void Encode(shared_ptr<string> &str)

補足として、shared_ptr::get()スマートポインターの目的を回避する生のポインターを生成するため、通常、呼び出すのはお勧めできません。の代わりにstr.get()、単に使用します*str

于 2013-03-04T00:19:41.137 に答える