2016-04-30 161 views
1

我想用unique_ptr沒有成功的數組。
聲明unique_ptr大小的正確方法是什麼?
(大小是一些參數)。C++ unique_ptr和數組

unique_ptr<A[]> ptr = make_unique<A[]>(size); 

下面是一個例子:

#include <iostream> 
#include <string> 
#include <vector> 
#include <functional> 
#include <memory> 

using namespace std; 

class A { 
    string str; 
public: 
    A(string _str): str(_str) {} 
    string getStr() { 
     return str; 
    } 
}; 

int main() 
{ 
    unique_ptr<A[]> ptr = make_unique<A[]>(3); 
} 

這不是工作,但是,如果我刪A的構造函數,它的工作原理。
我想3代表數組的大小,而不是A的構造函數的參數,我該如何做到這一點?

+0

提示:使用4個空格縮進標記文本代碼 – Drop

+1

爲什麼不使用'std :: unique_ptr > ptr = make_unique >(3);'? –

+0

或者'std :: unique_ptr > ptr = make_unique >();' –

回答

1

但是,這不起作用,如果我刪除了A的構造函數,它的作用就是 。

當您刪除用戶定義的構造函數時,編譯器將隱式生成一個默認構造函數。當您提供用戶定義的構造函數時,編譯器不會隱式地生成默認構造函數。

std::make_unique<T[]>需要使用默認構造函數...

所以,提供一個和所有應該工作以及

#include <iostream> 
#include <string> 
#include <vector> 
#include <functional> 
#include <memory> 

using namespace std; 

class A { 
    string str; 
public: 
    A() = default; 
    A(string _str): str(_str) {} 
    string getStr() { 
     return str; 
    } 
}; 

int main() 
{ 
    unique_ptr<A[]> ptr = make_unique<A[]>(3); 
} 
+0

在這種情況下,3代表ptr的大小?即,ptr現在包含3個指針? – user5618793

+1

@ user5618793這就是答案;如果你沒有意識到它,當你的類中沒有其他構造函數時,就會有一個隱式定義的默認構造函數,這就是爲什麼當你註釋掉用戶定義的構造函數時你的代碼工作的原因。 –

+0

@bku_drytt我知道,我只是沒有看到在我的代碼中使用'A()'< - 空構造函數,所以我不明白錯誤 – user5618793