如何用shared_ptr替换c指针?

时间:2016-02-29 16:09:31

标签: c++11

我是C ++ 11的新手,所以请你好。

你能告诉我一个简单的例子,shared_ptr如何取代标准指针?我也很感激,如果在这种情况下没有意义的解释。

e.g。你能改变这段代码吗?

Public Sub WriteAndReadFromListBox()

Dim lngRow As Long

' Adding 21 rows of 'hello world' in two columns
Load UserForm1
For lngRow = 0 To 20
    UserForm1.ListBox1.AddItem
    UserForm1.ListBox1.List(lngRow, 0) = "hello"
    UserForm1.ListBox1.List(lngRow, 1) = "world"
Next lngRow

' Selecting the first row allows you to use the
' .Value property and get 'hello' (from the first column)
UserForm1.ListBox1.Selected(0) = True
Debug.Print UserForm1.ListBox1.Value

' The following lines of code will write the entire content
' of the ListBox to the sheet with the Index 1
For lngRow = 0 To UserForm1.ListBox1.ListCount
    Sheets(1).Cells(lngRow + 1, 1).Value2 = UserForm1.ListBox1.List(lngRow, 0)
    Sheets(1).Cells(lngRow + 1, 2).Value2 = UserForm1.ListBox1.List(lngRow, 1)
Next lngRow

UserForm1.Show

End Sub

- >

std::vector <CVariant*>liste;
liste.push_back( new CVariant( (unsigned int) 24, Parameter1", TYPE_UINT) );
std::cout << liste.at(0)->get<int>() <<"\n";
delete liste.at(0);

???

2 个答案:

答案 0 :(得分:2)

如果我没错,你应该这样做:

std::vector<std::shared_ptr<CVariant>> liste;

liste.push_back( std::make_shared<CVariant> (arguments...));

选中此link

希望这有帮助。

答案 1 :(得分:2)

如果您有这样的矢量列表

std::vector < std::shared_ptr<CVariant> >liste;

您应该使用共享指针而不是指针调用liste.push_back方法。您可以在c中初始化共享指针:

auto pointer = std::make_shared<CVariant>( (unsigned int) 24, Parameter1", TYPE_UINT );

Ant将指针添加到列表中,如下所示:

liste.push_back( pointer );