Right way to initialize a pointer in a constructor

后端 未结 3 949
一向
一向 2021-01-28 10:40

I have the following exercise:

Add code to make it run properly.

class MyInt
{
public:

private:
    int* MyValue;
}

int main(int argc,char** a         


        
相关标签:
3条回答
  • 2021-01-28 10:58

    I'm not really sure why you want to store a pointer to an int inside a class, rather than just storing the value directly (and not have a pointer be the input to the constructor), but assuming you do actually want that, here's how you'd do it:

    MyInt(int x):MyValue(new int(x)){}
    

    But this is really, really terrible style, and you have to have a good reason for doing it. You also need to remember to free the pointer at class destruction:

    ~MyInt(){delete MyValue;}
    
    0 讨论(0)
  • 2021-01-28 11:09

    I don't see anything in your original problem statement that requires the pointer to be initialized to the address of an int. The minimal code required to fix the example would be to add a constructor that takes an int, and initialize MyValue to nullptr.

    class MyInt
    {
    public:
        MyInt(int) {}
    private:
        int* MyValue = nullptr;
    };
    
    int main(int argc,char** argv)
    {
     MyInt x(1);
     return 0;
    }
    

    If your compiler doesn't support C++11 then

    class MyInt
    {
    public:
        MyInt(int) : MyValue(NULL) {}
    private:
        int* MyValue;
    };
    
    0 讨论(0)
  • 2021-01-28 11:19

    Another way:

    MyInt(int x) : MyValue(new int(x)) {}
    

    This doesn't require the additional member. However, you have to make sure that you deallocate the memory in the destructor.

    ~MyInt() { delete MyValue; }
    
    0 讨论(0)
提交回复
热议问题