2

I have a question that how i can avoid the destruction in class. I have the sample code C++ here:

class Array {
    int *p;
    int n;
public:
    Array(int n_ = 0) {
        p = new int[n_];
    }
    ~Array(void) { 
        cout << "Deleted" << endl; delete []p;
    }
    friend Array operator+(Array A, Array B)        // the amount of elements A and B are the same
    {
        Array S(A.n);
        for(int i=0; i < A.n; i++)
            S.p[i] = A.p[i] + B.p[i];
        return S;     // object S has been destroyed before returned.
    }
};

In here, when the object has got the value and return. But object S have been destroyed by destruction before returned. Can anyone help me to avoid the destruction or some way for the object S can be returned to main. Thanks

Vinh Trieu
  • 993
  • 8
  • 12

2 Answers2

2

You can either define a move and/or a copy constructor (if it is not implicitly defined) and the value will be moved/copied before its destruction.

hrkz
  • 378
  • 3
  • 14
  • Thanks for your answer but If i use the copy constructor way, it will waste time for copy. Because if we apply it for n = 1000, it will spend O(1000), i don't want waste the time for copy – Vinh Trieu Apr 27 '15 at 10:36
  • Then you can use move semantics to avoid the copy, which will be way faster – hrkz Apr 27 '15 at 10:48
  • If you look at my answer, compiler adopts another optimization, before the move semantics. – Mouze Apr 27 '15 at 10:50
0

You can provide a copy ctor, than it will turn out that your compiler never call it, due to NRVO (named Return Value Optimization).

Read this wiki: http://en.wikipedia.org/wiki/Return_value_optimization

With C++11 o C++14, you can use the move semantics, a general technique to move expensive objects.

Mouze
  • 706
  • 5
  • 10
  • Yes, i think so. But in the scenario, i have many elements in the object, i will waste much time for doing the copy for object. – Vinh Trieu Apr 27 '15 at 10:45
  • This is t really a move-only class though. I found that at least with gcc, RVO is still used if you have a move constructor but not a copy constructor. However, as soon as you put std::move on the return line the standard requires the move constructor to be run – evan Apr 27 '15 at 11:21
  • Can you write down for me. I wrote it return std::move(S); But it was also destroyed. – Vinh Trieu Apr 27 '15 at 15:56