繁体   English   中英

错误:没有匹配函数可调用默认副本构造函数?

[英]error: no matching function for call to default copy constructor?

我的类中有一个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_;

映射键始终为const,并且您的声明完全等同于

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

boost :: mutex是不可复制的。 由于Tick具有一个作为数据成员,因此这使得Tick也不可复制。 反过来,这使得地图不可复制。

因此,要使Logger复制,您必须提供自己的复制构造函数,并在其中构造profilers_的适当副本。 或者,也许更合适(由于使用@LightnessRacesInOrbit的建议),而是为Tick提供合适的副本构造函数。

问题是boost :: mutex是不可复制的。 因此,如果您不提供复制构造函数,则编译器会尝试生成默认构造函数。 这个默认值需要复制所有成员,但是不能复制boost :: mutex,所以它放弃了。 您的复制构造函数不会复制互斥体。 相反,它默认初始化新的,因此可以正常工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM