为什么我可以在这个独特的指针中声明一个新角色数组?
我正在尝试为对象制作运行时ID。我已经使用常规指针完成了它,但是我需要通过独特的指针使其使用。为什么我不能在唯一的指针中使用新
?我明白了
错误e0079期望类型指定符。
在此行:
unique_ptr<char> idPtr(new char[DEVICE_ID_LENGTH]);
这是完整的文件:
#pragma once
#include <iostream>
#include <string>
#include <memory>
#include <utility>
using namespace std;
constexpr auto DEVICE_ID_LENGTH = 10;
class Widget
{
public:
//constructor
explicit Widget(int nbr);
~Widget();
void getID(char* s, const int len);
std::string WhatIAm;
//char* idPtr = new char[DEVICE_ID_LENGTH]; //This needs to be initialized by the constructor
unique_ptr<char> idPtr(new char[DEVICE_ID_LENGTH]);
int getSize();
private:
int widgetSize;
int widgetNumber;
};
I'm trying to make a runtime id for an object. I have it done using a regular pointer, but I need to make it work with a unique pointer. Why can't I use new
in the unique pointer? I get
Error E0079 expected a type specifier.
On this line:
unique_ptr<char> idPtr(new char[DEVICE_ID_LENGTH]);
Here is the full file:
#pragma once
#include <iostream>
#include <string>
#include <memory>
#include <utility>
using namespace std;
constexpr auto DEVICE_ID_LENGTH = 10;
class Widget
{
public:
//constructor
explicit Widget(int nbr);
~Widget();
void getID(char* s, const int len);
std::string WhatIAm;
//char* idPtr = new char[DEVICE_ID_LENGTH]; //This needs to be initialized by the constructor
unique_ptr<char> idPtr(new char[DEVICE_ID_LENGTH]);
int getSize();
private:
int widgetSize;
int widgetNumber;
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来自 cppReference 关于默认成员初始化(BOLD PLOASESIS INICER):
请注意,此处不允许使用括号的默认会员初始化。相反,它被解释为成员函数声明,因此预期打开括号参数列表,但您提供
new
expression,因此您的编译器正确地抱怨参数列表时似乎没有空,它看不到第一个参数的类型说明符。另请注意,您需要
unique_ptr&lt&gh []&gt;
,而不是unique_ptr&lt; char&gt;
,以管理由新表达式阵列创建的数组,以便其destructor知道它必须调用delete []
,而不是delete
,用于持有指针。因此,要执行默认会员初始化,可以使用,例如,例如,
使用命名空间std; 是不良练习,通常是尤其是 。参见在这里。
From cppreference about default member initializers (bold emphasis mine):
Note that default member initialization using parentheses like in your code is not allowed here. Instead, it is interpreted as member function declaration, thus after opening bracket parameter list is expected, but you provide
new
-expression, so your compiler correctly complains that while your parameter list doesn't seem empty, it doesn't see type specifier for the first parameter.Also note that you need
unique_ptr<char[]>
, notunique_ptr<char>
, to manage arrays created by array form of new expression, so that its destructor knows it has to calldelete[]
, notdelete
, for held pointer.So, to perform default member initialization like you want, you can use, e.g., braced initializer like this:
P.S.
using namespace std;
is bad practice usually, especially in header files. See here.