C ++ unique_ptr和数组 [英] C++ unique_ptr and arrays

查看:161
本文介绍了C ++ unique_ptr和数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用带有unique_ptr的数组,但没有成功。

声明某种大小的unique_ptr的正确方法是什么?

(大小有些参数)。

I'm trying to use arrays with unique_ptr with no success.
What is the correct way to declare a unique_ptr of some size?
(size is some paramter).

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的构造函数的参数,我如何做到这一点?

This is not working, however, if I delete the constructor of A, it works.
I want the 3 to represent the size of the array, and not an argument to A's constructor, how do I make that happen?

推荐答案


这不起作用,但是,如果我删除A的构造函数,则
可以工作。

This is not working, however, if I delete the constructor of A, it works.

当删除用户定义的构造函数时,编译器将隐式生成一个默认的构造函数。提供用户定义的构造函数时,编译器不会隐式生成默认的构造函数。

When you removed the user defined constructor, the compiler implicitly generates a default one. When you provide a user defined constructor, the compiler doesn't implicitly generate a default constructor.

std :: make_unique< T []> 要求使用默认构造函数。

std::make_unique<T[]> requires the use of default constructors...

所以,提供一个,一切都应该正常工作

So, provide one, and all should work well

#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);
}

这篇关于C ++ unique_ptr和数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆