Emanuele Paolini
Emanuele Paolini

Reputation: 10162

inserting object in a map without copying the object

Is it possible to insert objects in a map, if the class of the object has disabled copy constructor and disabled copy operator? Is move semantics useful here?

#include <map>

class T {
public:
  T(int v): x(v) {};
private:
  T(const T &other); // disabled!
  T &operator=(const T &other); // disabled!
  int x;
};

int main() {
  std::map<int, T> m;
  m[42] = T(24);  // compilation error here!
}

edit I was not completely clear. The object is huge, so I don't want to make unnecessary copies of it. But I can modify the code of the class (maybe I need to implement move semantics?) and not the user code (the main function in the example).

Upvotes: 3

Views: 809

Answers (3)

Zolt&#225;n
Zolt&#225;n

Reputation: 708

You might insert as pointer:

public:
    T(int v) : x(v) {};
    int getX(){ return this->x; }
private:
    T(const T &other); // disabled!
    T &operator=(const T &other); // disabled!
    int x;
};

int main() 
{
    std::map<int, T*> m;

    m[42] = new T(24);  // no compilation error here!

    std::cout << m[42]->getX() << std::endl; // prints out 24

    return 0;
}

Upvotes: 0

Simia_Dei
Simia_Dei

Reputation: 76

This might be what you are looking for:

class T {
public:
  T(){};
  T(int v): x(v) {};
  T(const T &other) = delete;
  T(T&& other) {x = other.x; std::cout << "move ctor\n";}
  T &operator=(const T &other) = delete;
  T& operator=(T&& other) {x = other.x; std::cout << "move assigment\n";}
 private:
  int x;
};

int main() {
  std::map<int, T> m;
  m.insert(std::make_pair(42, T(24))); 
  m[44] = T(25);
}

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 477010

Use emplacement syntax:

m.emplace(std::piecewise_construct,
          std::forward_as_tuple(42), std::forward_as_tuple(24));
//                              ^^                         ^^
//                            int(42)                     T(24)

Or, in C++17, use try_emplace:

m.try_emplace(42, 24);

Upvotes: 4

Related Questions