1

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;
};
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
RVoccio
  • 11
  • 2

1 Answers1

1

From cppreference about default member initializers (bold emphasis mine):

Non-static data members may be initialized in one of two ways:

  1. ...
  2. Through a default member initializer, which is a brace or equals initializer included in the member declaration and is used if the member is omitted from the member initializer list of a constructor.

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[]>, not unique_ptr<char>, to manage arrays created by array form of new expression, so that its destructor knows it has to call delete[], not delete, for held pointer.

So, to perform default member initialization like you want, you can use, e.g., braced initializer like this:

unique_ptr<char[]> idPtr{new char[DEVICE_ID_LENGTH]};

P.S. using namespace std; is bad practice usually, especially in header files. See here.

YurkoFlisk
  • 873
  • 9
  • 21