![](/img/trans.png)
[英]Assign std::vector<std::unique_ptr<T>> to another std::vector<std::unique_ptr<T>>
[英]What happens when std::make_unique<T>() assigns to std::unique_ptr<T>?
我對std :: unique_ptr有疑問。
當我們分配沒有參數的std :: make_unique()時,會發生什么?
例如,
struct A {
int a, b;
A() {}
A(int w, int e) : a(w), b(e) {}
};
int main() {
A h(1, 2);
std::unique_ptr<A> hello = std::make_unique<A>();
std::cout << hello->a << std::endl;
}
在上面的代碼中,我提到了默認構造函數,我將hello-> a的輸出作為垃圾值(隨機負值)
但是,當我如下更改結構時,
struct A {
int a, b;
A() {a=0;b=0;}
A(int w, int e) : a(w), b(e) {}
};
hello-> a的結果值為0。
為什么在使用std :: make_unique()時默認構造函數未將int分配為0?
傳遞給std::make_unique<A>()
的參數是傳遞給A
的相應構造函數的參數。 這里沒有提供任何內容,因此將調用A
的默認構造函數。
為什么在使用std :: make_unique()時默認構造函數未將int分配為0?
未初始化的內置類型成員保留不確定的值。 此行為與std::unique_ptr
或std::make_unique
; 這就是默認初始化內置類型的方式。
初始化它們:
struct A {
int a, b;
A(): a(0), b(0) {}
A(int w, int e) : a(w), b(e) {}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.