简体   繁体   English

创建一个没有默认构造函数的类的智能指针数组

[英]Create an array of smart pointers to a class with no default constructor

I'm referring to the question , Can we create an array of std::unique_ptr to a class which has deleted default constructor as below, How to pass the string argument. 我指的是这个问题 ,我们可以创建一个std::unique_ptr数组到一个已删除默认构造函数的类,如下所示,如何传递string参数。

#include <iostream>  
#include <string>  
#include <memory>

using namespace std;

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

int main()
{
    unique_ptr<A[]> ptr = make_unique<A[]>(3);
    unique_ptr<A[]> arr[3] = make_unique<A[]>(3);
    // Do something here
    return 0;
}

For an array of smart pointers: 对于一组智能指针:

unique_ptr<A> ptr[3];

for (auto& p : ptr)
    p = make_unique<A>("hello");

You can't do that with make_unique . 你不能用make_unique做到这make_unique But you can use this: 但你可以用这个:

unique_ptr<A[]> ptr(new A[3]{{"A"}, {"B"}, {"C"}});

Before C++11 - it was very hard (that can be done with placement new etc). 在C ++ 11之前 - 它非常难(可以通过放置新的等来完成)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何创建智能指针数组? - How to create an array of smart pointers? 在派生类构造函数中使用智能指针 - using smart pointers in a derived class constructor 如何在具有指向对象的指针的数组的类中创建复制构造函数和析构函数,其中对象本身具有指向int的指针的数组 - How to create copy constructor and destructor in a class with an array of pointers to objects where objects itself have an array of pointers to ints 如何使用 class 的智能指针创建指针矩阵? - How to create a matrix of pointers using smart pointers for a class? 从构造函数调用类函数还是使用智能指针? - Calling class functions from constructor or use smart pointers? 在具有智能指针的类上正确实现Copy构造函数和Equals运算符 - Proper Implementation of Copy Constructor and Equals Operator on a class with smart pointers 在具有模板构造函数的类中使用智能指针的Pimpl:奇怪的不完整类型问题 - Pimpl with smart pointers in a class with a template constructor: weird incomplete type issue 使用默认构造函数指向对象的数组 - Array of pointers to objects using the default constructor 隐式复制的构造函数智能指针 - Implicitly copied constructor Smart Pointers 虚拟构造函数成语与智能指针 - virtual constructor idiom with smart pointers
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM