---
title: Tensor
description: "Tensor类的构造函数。"
url: https://www.hiascend.com/document/detail/zh/Atlas200IDKA2DeveloperKit/latest/Application%20Development%20Guide/msadg/mxvisionug_0745.html
sourcePath: /source/zh/Atlas200IDKA2DeveloperKit/23.0.RC2/Application Development Guide/msadg/mxvisionug_0745.html
indexId: be16d47c1bc0412b01b0b78606b8e7307aa56539a88c002944e03f1e2e305458102
---
# Tensor

#### 函数功能

Tensor类的构造函数。


#### 函数原型

```
Tensor()   //默认构造函数。 构造失败时，会抛出std::runtime_error异常
```

```
Tensor(const Tensor &tensor); // 支持拷贝构造
```

```
Tensor(const std::vector<uint32_t> &shape, const MxBase::TensorDType &dataType, const int32_t &deviceId = -1)
//不传入内存，可搭配TensorMalloc接口进行内存申请，申请的内存无需用户管理释放。 构造失败时，会抛出std::runtime_error异常
```

```
Tensor(void* usrData,const std::vector<uint32_t> &shape, const MxBase::TensorDType &dataType, const int32_t &deviceId = -1)
//传入用户自己构造的数据内存，需要用户自身对此内存进行管理（保证内存数据的生命周期）。 构造失败时，会抛出std::runtime_error异常
```

```
Tensor(const std::vector<uint32_t> &shape, const MxBase::TensorDType &dataType, const int32_t &deviceId,
bool isDvpp);
```

```
Tensor(void *usrData, const std::vector<uint32_t> &shape, const MxBase::TensorDType &dataType,
const int32_t &deviceId, const bool isDvpp, const bool isBorrowed);
```

```
Tensor(const Tensor &tensor, const Rect &rect); // 带引用区域的拷贝构造
```


#### 参数说明

| 参数名 | 输入/输出 | 说明 |
| --- | --- | --- |
| tensor | 输入 | 已初始化的其它Tensor。 |
| usrData | 输入 | 用户构造的输入内存，该内存由用户管理申请和释放。 |
| shape | 输入 | Tensor的shape属性。 |
| dataType | 输入 | Tensor的数据类型，具体请参见TensorDType。 |
| deviceId | 输入 | Tensor所在的设备ID，默认为\-1，在Host侧。 当Tensor构造函数中使用“isDVPP”参数，此时deviceID无默认值，需根据实际情况输入。 如果传入用户指针“usrData”，该值需要与deviceId为同一侧内存（Host侧为“\-1”，Device侧为具体设备ID），否则后续业务存在风险和异常。 |
| isDvpp | 输入 | 设置是否申请DVPP的内存，“deviceId”如果为“\-1”，则申请Host侧内存，该参数设置无效。 如果传入用户指针“usrData”并且“isDvpp”设置为“true”，则需保证“usrData”指向的内存在Device侧，否则后续业务存在风险和异常。 |
| isBorrowed | 输入 | 设置是否将usrData指向的内存交由Tensor来释放，“isBorrowed”的值设为“false”，则由Tensor来释放usrData指向的内存，用户无需释放；“isBorrowed”的值设为“true”，则用户需要自行管理usrData指向的内存。 须知： 委托Tensor管理该内存，仅支持需要手动释放的内存，否则可能导致内存重复释放。 |
| rect | 输入 | 代表图片的引用区域坐标（x0, y0, x1, y1）左闭右开。 须知： 若采用Tensor(const Tensor &tensor, const Rect &rect)的方式进行构造，要求： tensor不能为空，仅支持NHWC、HWC和HW的tensor，通道数为1/3/4，batch维度为1。 rect区域x0,y0需要分别小于x1,y1；x0, y0, x1,y1需要在tensor的宽高范围内。 |
