Question

I'm trying to write a small application and have come across a compile time error using auto_ptr.

I originally tired creating a smart pointer with class I created but the same error occurs if I try and create a smart pointer of type int so there must be something else I'm doing wrong. I was following the example given here..

I've got a feeling the answer to this will result in me slapping myself.

I declare the smart pointer at the bottom of this file.

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <memory.h>
#include <QMainWindow>
#include "dose_calac.h"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    /*
     Some QT stuff here, removed for clarity / size...
    */

private:
    Ui::MainWindow *ui;

    /*
      Object for storage of data and calculation of DOSE index score.
    */

    std::auto_ptr<int> pdoseIn(new int); // A simple set case, but sill produces an error!?!

    std::auto_ptr<DOSE_Calac> pdoseIn(new DOSE_Calac); // Original code, error found here at first.
};

#endif // MAINWINDOW_H

and this is my class, dose_calac.h.

#ifndef DOSE_CALAC_H
#define DOSE_CALAC_H

class DOSE_Calac
{
public:
// constructor
    DOSE_Calac();
// set and get functions live here, removed for clarity / size.

// function for caulating DOSE indexpoints
    int CalcDOSEPoints();
private:
    unsigned int dyspnoeaScale;
    unsigned int fev1;
    bool smoker;
    unsigned int anualExacerbations;
    unsigned int doseIndexPoints;

};

#endif // DOSE_CALAC_H

Any help or suggestion gratefully received.

Was it helpful?

Solution

Your error is caused by including an incorrect header. Instead of

#include <memory.h>

you should write

#include <memory>

Also, there is more severe mistake in your class definition, because you cannot initialize class member in this way:

std::auto_ptr<int> pdoseIn(new int);

You have to, separately, declare it and initialize in the constructor:

std::auto_ptr<int> pdoseIn;
MainWindow()
    : pdoseIn(new int)
{}

OTHER TIPS

You can not initalize the class member variables like that, you need to define it in the class declaration by doing std::auto_ptr<int> a; and initialize it in ctor using a(new int).

You can't initialize data members inside the class declaration like this:

class MainWindow
{
    std::auto_ptr<int> pdoseIn(new int);
};

You need to declare the member like this, and initialize the data member in the constructor:

class MainWindow
{
    std::auto_ptr<int> pdoseIn;
    MainWindow ()
        : pdoseIn(new int)
    {
    }
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top