0

I am practising to execute move constructor every time by passing R-Value. But Sometimes the Deep copy constructor is getting called it is not supped to.

I am inserting an R-value object inside a vector. What is the logical flaw in this code?

I have tried debugging, I don't understand as to why deep copy constructor is called after the object was moved?

#include <iostream>
#include <string>
#include <vector>
using namespace std;
class example{
    private:
     int *pointer;
public:
    //constructor
    example(int d){
        pointer = new int;
        *pointer = d;
        cout<<"Constructor Called"<<endl;
    }


// deep copy
    example(const example &source){
        pointer = new int;
        *pointer= *source.pointer;
        cout<<"deep copy made"<<endl;
    }
// Move Constructor
    example(example &&source):pointer{source.pointer}{
    source.pointer = nullptr;
    cout << "object moved"<<endl;
    }
    ~example() {
        delete pointer;
        cout << "Destroyed"<<endl;
    }

};

int main()
{

    vector <example> vec;
    vec.push_back(example{300});
    vec.push_back(example{300});
    vec.push_back(example{300});
    vec.push_back(example{300});
    return 0;
}

If the code was right it will always use MOVE constructor, and it will avoid deep copy

M.M
  • 138,810
  • 21
  • 208
  • 365
  • 1
    try changing the move constructor to `example(example &&source) noexcept :` (and the rest the same) – M.M Mar 25 '19 at 01:11
  • But what does noexcept do? i found it from my course tutorial but the reason is not given – dark silence Mar 25 '19 at 01:21
  • 1
    @ZahidulAmin: The noexcept allows the library to use move. Because if an exception could happen, it would have to be undoable in order to leave the vector element in a safe state. – Zan Lynx Mar 25 '19 at 01:24

1 Answers1

2

Solved it adding NOEXCEPT resolved the issue

 example(example &&source) noexcept :pointer{source.pointer}  {
        source.pointer = nullptr;
        cout << "object moved"<<endl;
        }