Class Variable Dynamic Assignment in C++

Asked 2 years ago, Updated 2 years ago, 22 views

Like Python's class variable, C++ uses class variable, and I want to use it as a dynamic allocation.

#include <iostream>
class Some{
    private:
        static Some* _A;
    public:
        void __setSome(int n){
            this -> _A = new Some[n];
        }
};

int main(){
    Some A;
    A.__setSome(5);
}

A compilation error occurs when the code is woven as follows: What is wrong?

c++

2022-09-22 20:38

2 Answers

Before we begin, C++ does not have the name class variable and has the name static member variable.

I think there will be a link error, not a compilation error.

Static member variables must be defined once outside the class.

class Some{
    private:
        static Some* _A;
    public:
        void __setSome(int n){
            this -> _A = new Some[n];
        }
};
Some* Some::_A;

Using a smart pointer would be a little safer and more relevant to your intentions.

#include <iostream>
#include <memory>

class Some{
    private:
        static std::unique_ptr<Some[]> _A;
    public:
        void __setSome(int n){
            _A.reset(new Some[n]);
        }
};

std::unique_ptr<Some[]> Some::_A;

int main(){
    Some A;
    A.__setSome(5);
}

This method will automatically release the memory at the end of the program.

If C++11 is not available, there is a way as follows.

#include <iostream>

class Some{
    struct Ptr {
        Some* ptr;
        Ptr() : ptr() {}
        ~Ptr() { delete[] ptr; }
        void reset(Some* p) {
            delete[] ptr;
            ptr = p;
        }
        Some& operator[](std::size_t i) { return ptr[i]; }
        Some* operator->() { return ptr; }
        Some& operator*() { return *ptr; }
    };
    private:
        static Ptr _A;
    public:
        void __setSome(int n){
            _A.reset(new Some[n]);
        }
};

Some::Ptr Some::_A;

int main(){
    Some A;
    A.__setSome(5);
}


2022-09-22 20:38

You applied Python naming convention to c++...

C++ and Python are different languages.

First, the compilation error will come from static Some* _A;. Static refers to a class variable. Also, because initialization is missing, you're probably referring to the garbage price (address.

Some* _A = NULL;

It's explicitly initialized like this.

If static removal and initialization are performed, there will be no compilation error.

However, in the example above, memory leaks can occur.

void __setSome(int n){
    this -> _A = new Some[n];
}

In the __setSome method, create n Some objects on the heap. Where should I release (remove)?

In c++, this type of code is quite dangerous.

At the very least, you should explicitly remove it using a decipitator or use a smart pointer to handle it.

~Some(){
   // // if(_A != NULL) delete[] _A;
   If(!_A) delete[] _A; // This would be a better way.
}


2022-09-22 20:38

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.