小编dan*_*iel的帖子

避免在没有原始指针的情况下复制地图的密钥

每次在std :: map中插入一对,其键是std :: string时,它会生成两个副本.您可以避免使用原始指针,但它是异常不安全的.有没有办法使用智能指针而不是原始指针?

示例代码:

// To compile: g++ -std=c++0x exmaple.cpp -o example 

#include <iostream>
#include <string>
#include <map>
#include <memory>

class StringSquealer: public std::string
{
  public:
    StringSquealer(const std::string s) : std::string(s) {}
    StringSquealer(const StringSquealer&) 
    { 
      std::cout << "COPY-CONSTRUCTOR" << std::endl; 
    }
};

int main()
{
  // Inefficient
  std::map<StringSquealer,int> m1;
  m1[StringSquealer("key")] = 1;
  std::cout << "---" << std::endl;

  // Exception-unsafe
  std::map<StringSquealer*,int> m2;
  m2[new StringSquealer("key")] = 1;

  //Ideal??
  std::map<std::unique_ptr<StringSquealer>,int> m3;
  std::unique_ptr<StringSquealer> s(new StringSquealer("key"));
  //!m3[std::move(s)] = 1;  // No compile
} …
Run Code Online (Sandbox Code Playgroud)

c++ smart-pointers stdmap stdstring c++11

3
推荐指数
1
解决办法
878
查看次数

标签 统计

c++ ×1

c++11 ×1

smart-pointers ×1

stdmap ×1

stdstring ×1