簡體   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