c++ - 为类 move 构造函数和 move 赋值运算符

标签 c++ c++11 gcc move-semantics

我正在尝试为嵌入式设备编译以下代码(它是来自 TI 的交叉编译器,具有 C++11 (C++0) 的实验性支持)。目标:

arm-arago-linux-gnueabi Thread model: posix gcc version 4.5.3 20110311 (prerelease) (GCC)


无法编译 move 构造函数和 move 赋值运算符的默认说明符(/home/user/test/main.cpp:40:26: error: 'th& th::operator=(th&&)' cannot be defaulted).

std::make_unique & emplace_back 没有实现,那些不可用。

我需要更改代码中的哪些内容才能使其适用于该平台?

class th {
    public:
        void func() {
            sleep(3);
            *this->progress = 100;
        }

        th(int* prog) :
            progress(prog), 
            m_thread(std::thread(&th::func, this)) {};

        th(th const& other) = delete;
        th(th && other) = default;
        th& operator=(th const& other) = delete;
        th& operator=(th &&) = default;

        void join() { m_thread.join(); }
        int *progress;

    private:
        std::thread m_thread;
};

int main(void) {

        std::vector<int> progress;
        progress.push_back(-1);
        progress.push_back(-1);

        std::deque<std::unique_ptr<th>> deq;

        std::cout << "progress[0]:" << progress[0] << std::endl;
        std::cout << "progress[1]:" << progress[1] << std::endl;

        std::cout << "executing threads..." << std::endl;

        for(size_t i = 0; i < 2; ++i) {
            deq.push_back(std::unique_ptr<th>(new th(&progress[i])));
        }

        while(true) {
            std::cout << "SIZE:" << deq.size() << std::endl;

            if(deq.size() == 0)
                break;

            for (std::deque<std::unique_ptr<th>>::iterator it = deq.begin(); it != deq.end(); it++) {
                //std::cout << (*it)->progress << std::endl;
                if(*((*it)->progress) == 100) {
                    std::cout << "JOIN & DELETE" << std::endl;
                    (*it)->join();
                    deq.erase(it);
                }
                else {
                    std::cout << "STILL RUNNING" << std::endl;
                }
                    //std::cout << *((*it)->progress) << std::endl;
            }
            sleep(1);
        }

    exit(EXIT_SUCCESS);
}

最佳答案

gcc 4.5.x 不支持生成 move 特殊成员函数,see N3053 for more details , 还有 https://gcc.gnu.org/gcc-4.5/cxx0x_status.html对于 gcc C++11 支持功能,因此您对编译器不满意。您的代码在 gcc5/6 和 clang 上编译良好,实时查看 here .

一种选择是完全删除这些行

th(th const& other) = delete;
th(th && other) = default;
th& operator=(th const& other) = delete;
th& operator=(th &&) = default;

让编译器完成工作并为您生成特殊的成员函数。顺便说一句,默认情况下将删除复制构造函数和复制赋值运算符,因为 std::thread 是不可复制的。

关于c++ - 为类 move 构造函数和 move 赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41410249/

相关文章:

c++ - CLOCKS_PER_SEC 与 std::clock() 的结果不匹配

c++ - c++ 11中结构数组的大括号初始化

c++ - 使用非常量函数参数初始化数组

c++ - 由于 64 位 DLL,Win32 应用程序和错误 0xC0000007b

c++ - move 参数或以通常的 C++98/03 方式传递它们?

c++ - 为什么要在方法的定义中使用 throw?

c++ - 如何加快从流到内存的读取行?

linux - 如何更改 Ubuntu 中的默认 GCC 编译器?

c++ - 线性同余发生器 : How important is setting seed?

c++ - 如何在 C++/CLI 项目中包含 JpegBitmapDecoder^