문제

I have once asked this question and after hours of research I think the answers are not suitable and do not fix my issue. Please inspect this code:

 #include <iostream>
using namespace std;

class Test
{
public:
    Test();
    Test(int);
    ~Test();
    friend Test Problem();
    int get_a ();
private:
    int* a;
};

Test::Test(int x)
{
    a = new int[1];
    *a = x;
}

Test::~Test()
{
    delete [] a;
}

Test Problem()
{
    Test doomed(1);
    int* doomed_too = new int[1];
    *doomed_too = 99;
    doomed.a = doomed_too;
    return doomed;
}

int Test::get_a()
{
    return *a;
}

int main()
{
    Test Sniffer = Problem();
    if (Sniffer.get_a() == 99) cout << "You saved me! Thanks!";
    return 0;
}

Yes, I know that object doomed will be destroyed before returned to object Sniffer, so Sniffer will get random value from the freed memory of the Heap. My issue is - how to save the "life" of this object doomed? Can you provide working code/"fix"?

Furthermore, I know this specific example has many workarounds but on the project I am working on I am not allowed to do such workarounds (no strings, no vectors, just dynamic array of ints without using further libraries and complications).

I will be glad if you can test your solution first (before answering).

I did lot of research on this topic and I am amused that all the lectures and examples always use not-dynamic private members or if they use in their examples dynamic private members they always "skip" to show operator+ overloading or operator* overloading (just examples).

How can we make operator+ overloading public-member function of a given Class, if the same Class do posses a dynamic private-member - for example int* n?

도움이 되었습니까?

해결책

You should implement a copy constructor:

Test::Test(const Test& other)
{
  this->a = new int;
  *this->a = *other.a;
}

Some other problems:

  • why you create a = new int[1]? it should be just a = new int

  • if you really need a = new int[1] the corresponding delete for arrays in C++ should usually be delete [] a.

Alternatively, you can use a smart pointer (std::tr1::shared_ptr or similar, depending on your compiler), see http://en.cppreference.com/w/cpp/memory/shared_ptr

다른 팁

Without a custom copy constructor and copy assignment operator, you are creating multiple objects that point to the same memory. That's the source of your problem.

Whenever you have a class that allocates memory for its member data in its constructor, you also need to implement the copy constructor and copy assignment operator. Please read The Rule of Three.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top