Overloading new returns wrong address

后端 未结 1 1086
我寻月下人不归
我寻月下人不归 2021-01-29 15:27
#include 
using namespace std;

class station{
    int n;
    float *p;
public:
    station(){};
    station(const station &ob){cout<<\"Copy\";         


        
相关标签:
1条回答
  • 2021-01-29 15:34

    When using the new[] operator, the compilers can allocate some extra space for the internal bookkeeping (to store e.g. the array size, so when calling delete[], it will know how many object to destroy). That is the difference you see between the "raw" allocation and the final array allocated object address.

    That is also the reason, why you should not call delete on a memory allocated via new[] and vice versa, as it might result in memory leaks (only fist object destroyed), accessing invalid data and/or freeing a bad pointer (technically all UB).


    EDIT

    As for the object contents issues, you are not supposed to initialize the objects in the operator new[] like this

    for(int i=0;i<b;i++){
        cin>a[i];
    }
    

    the operator new/new[] is just to allocate the "raw" memory.

    Simply remove that and read the object in the constructor if you wish to (the constructors are called by the compiler automatically for each object in the array), e.g.:

    station(){cin >> *this}; // or '>' if you really want to keep that
    

    But in general, the reading from stream is usually done explicitly, so you can do for example:

    a=new station[2];
    for(int i=0;i<2;i++){
        cin>a[i];
    }
    

    in the main().

    0 讨论(0)
提交回复
热议问题