Search code examples
c++initializationunique-ptrmember-initialization

unique_ptr can't initialize


I have the following code in a project, and it gives me an error C2059, syntax error "new" that the unique_ptr line is wrong.

#include <memory>

class Nothing {
public:
    Nothing() { };
};
class IWriter
{
    public:
        IWriter() {
        }

        ~IWriter() {
        }
    private:
        std::unique_ptr<Nothing> test(new Nothing());
};

What is happening here?


Solution

  • You're trying to use default member initializer, but in the wrong way. It must be simply a brace initializer (or equals initializer) (included in the member declaration).

    You could use list initialization (since C++11):

    std::unique_ptr<Nothing> test{ new Nothing() };
    

    Or member initialization list:

    class IWriter
    {
        public:
            IWriter() : test(new Nothing) {
            }
            ~IWriter() {
            }
        private:
            std::unique_ptr<Nothing> test;
    };