c++ - 错误 : no matching function for call to default copy constructor?

标签 c++ copy-constructor stdmap

我的类中有一个 std::map 容器变量,其中填充了我的嵌套类的对象:

class Logger {
private:
//...
    class Tick{
        ///stores start and end of profiling
        uint32_t start, lastTick,total;
        /// used for total time
        boost::mutex mutexTotalTime;
        ///is the profiling object started profiling?
        bool started;
    public:
        Tick(){
            begin();
        }
        /*
        Tick(const Tick &t){
            start = t.start;
            lastTick = t.lastTick;
            total = t.total;
            started = t.started;
        }
        */
        uint32_t begin();
        uint32_t end();
        uint32_t tick(bool addToTotalTime = false);
        uint32_t addUp(uint32_t value);
        uint32_t getAddUp();

    };
    std::map<const std::string, Tick> profilers_;
//...
public:
//...
Logger::Tick & Logger::getProfiler(const std::string id)
{
    std::map<const std::string, Tick>::iterator it(profilers_.find(id));
    if(it != profilers_.end())
    {
        return it->second;
    }
    else
    {
        profilers_.insert(std::pair<const std::string, Tick>(id, Tick()));
        it = profilers_.find(id);
    }
    return it->second;
}
//...
};

如果我不提供复制构造函数,上面的代码将无法编译,而我认为默认的复制构造函数应该已经到位了?! 我错过了什么概念吗? 谢谢

最佳答案

只有当你的类的所有成员都是可复制的时,才会为你生成复制构造函数。在 Tick 的情况下,您有一个对象

boost::mutex mutexTotalTime;

不可复制,所以编译器不会生成复制构造函数。请注意,在您注释掉的复制构造函数中,您没有复制互斥体——因为您知道您不应该这样做。编译器不知道这一点。

作为旁注,没有必要为映射键明确说明 const:

std::map<const std::string, Tick> profilers_;

映射键总是常量,你的声明完全等同于

std::map<std::string, Tick> profilers_;

关于c++ - 错误 : no matching function for call to default copy constructor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25359302/

相关文章:

c++ - 关于复制构造函数和 NRVO

具有通用键的 C++ std::map 类

基于宏函数参数的c++宏输出类型

c++ - iOS - 在 C++ 中获取可写路径

c++ - 在 Boost::range 中组合适配器

c++ - 我可以在 C++ 桌面游戏中使用 crashlytics 吗?

具有构造函数定义但没有实现代码的c++类?

c++ - 为什么以及何时删除复制构造函数和 operator=

c++ - 将元素插入 std::map 而无需额外复制

c++ - std::map::size_type 对于 std::map 其 value_type 是它自己的 size_type