![](/img/trans.png)
[英]C++: references and smart pointers - is there such a thing as a smart reference?
[英]C++ polymorphic pointers created in for loop refer to the same thing, is this because I'm not using smart pointers?
我的程序中有一個基類和兩個子類。 我是C ++的新手,沒有類似以下循環的內容:
baseclass * arr[10];
for (i = 0; i < 10; i++) {
if (some condition) {
SubclassA subA;
subA = SubclassA(stuff);
arr[i] = &subA;
}
else if (some other condition) {
SubclassB subA;
subB = SubclassB(stuff);
arr[i] = &subB;
}
}
當我運行代碼並首先創建SubclassA並將其地址分配給我的數組時。 但是,我發現發生了以下情況:在上一步之后,當我稍后在循環中創建SubclassB時,出於某種原因,SubclassB在與SubclassA所在的同一內存位置生成:它完全覆蓋了我的第一個對象我不明白為什么。
在C ++中, subA = SubclassA(stuff);
並不意味着要分配和創建一個全新的對象,然后為其分配引用。 subA
是一個本地對象,到達封閉}
將消失。 您不能將其地址存儲到陣列中。
您需要實際分配新的對象new
,最好使用智能指針來控制所有權和壽命:
Typedef std::array<std::unique_ptr<baseclass>, 10> ArrType;
ArrType arr;
for (i = 0; i < 10; i++)
{
if (some condition)
{
arr[i] = ArrType::value_type(new SubclassA(stuff));
}
else if (some other condition)
{
arr[i] = ArrType::value_type(new SubclassB(stuff));
}
}
您需要使用指針並創建new
對象以添加到數組中,而不是使用本地對象。
baseclass * arr[10];
for (i = 0; i < 10; i++) {
if (some condition) {
arr[i] = new SubclassA(stuff);
}
else if (some other condition) {
arr[i] = new SubclassB(stuff);
}
}
並且不要忘記,完成操作后,您需要遍歷數組並刪除指針。
for (i = 0; i < 10; i++) {
delete arr[i];
}
嘗試在子類中使用new
baseclass * arr[10];
for (i = 0; i < 10; i++) {
if (some condition) {
SubclassA subA = new SubclassA(stuff);
arr[i] = subA;
}
else if (some other condition) {
SubclassB subB = new SubclassB(stuff);
arr[i] = subB;
}
}
您正在存儲指向局部變量subA
和subB
指針。 當變量超出范圍時,對象將被刪除,並且指針將懸空。
要修復它,您必須使用動態內存分配。 建議使用智能指針(如std::unique_ptr
管理動態分配的內存。
std::vector<std::unique_ptr<baseclass>> arr;
for (int i = 0; i < 10; i++) {
if (some condition) {
arr.push_back(std::make_unique<SubclassA>());
} else if (some other condition) {
arr.push_back(std::make_unique<SubclassB>());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.