2016-03-09 58 views
3

如果對象的類已禁用了複製構造函數並禁用了複製操作符,是否可以在地圖中插入對象?移動語義在這裏有用嗎?在不復制對象的情況下在地圖中插入對象

#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! 
} 

編輯我並不完全清楚。該對象是巨大的,所以我不想做不必要的副本。但我可以修改類的代碼(也許我需要實現移動語義?),而不是用戶代碼(示例中的主函數)。

+1

還要注意'm [42]'也需要'T'默認構造函數。 – Jarod42

回答

1

這可能是你在找什麼:

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); 
} 
+0

我認爲這是我首選的解決方案......在接受之前等待可能的評論 –

4

使用進駐語法:

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

或者,在C++ 17,使用try_emplace

m.try_emplace(42, 24); 
0

你可能會插入指針:

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; 
} 
相關問題