【问题标题】:error: passing ‘const sdf’ as ‘this’ argument discards qualifiers [-fpermissive]错误:将“const sdf”作为“this”参数传递会丢弃限定符 [-fpermissive]
【发布时间】:2018-07-12 05:20:21
【问题描述】:

我正在尝试执行此代码。我认为这很简单,但我遇到了这个错误,我无法弄清楚:

// THIS IS THE MAIN FILE ////////
/////////////////////////////////

#include <iostream>
#include "sdf_func.hpp"
#include "single_task_func.hpp"
using namespace std;


int main() {
    sdf obj1;
    s_task cgh;
    cgh.single_task([=] {
        for (int i=0; i<30; i++) {
            obj1.sdf_write(10);
        };
    });
    cgh.single_task([=] {
        for (int i=0; i<30; i++) {
            obj1.sdf_write(10);
        };
    });
    return 0;
};      

// THIS IS SDF_FUNC.HPP ////////////////////
////////////////////////////////////////////
#include <iostream>
using namespace std;


class sdf {
int done;
public:
    sdf() : done(0) {};
    void sdf_write (int size) {
        static int wr_count = 0;
        if (wr_count == size) {
            done++;
        }
        wr_count++;
        cout << wr_count;
    };
};


// THIS IS SINGLE_TASK_FUNC.HPP///////////////////
//////////////////////////////////////////////////
#include <iostream>
#include <thread>
using namespace std;

class s_task {

struct task {

    void schedule (std::function<void(void)> f) {
        auto execution = [=] { f(); };
        std::thread thread(execution);
        thread.detach();
    };
};

task *task1;

public:
  void single_task(std::function<void(void)> F) {
    task1->schedule(F);
  }
};

我正在尝试运行 2 线程。但是由于某种原因,当我尝试从 main 调用 lambda 函数“single_task”时。它给了我这个错误:

错误:将“const sdf”作为“this”参数传递会丢弃限定符 [-fpermissive] obj1.sdf_write(10);

【问题讨论】:

  • 您不能在 const 对象上调用 non-const 成员函数。

标签: c++


【解决方案1】:
cgh.single_task([=] {
    for (int i=0; i<30; i++) {
        obj1.sdf_write(10);
    };
});

应该是:

cgh.single_task([=] mutable {
    for (int i=0; i<30; i++) {
        obj1.sdf_write(10);
    };
});

来自lambda

mutable:允许body修改copy捕获的参数,并 调用它们的非常量成员函数

由于sdf_write 是一个非常量方法,所以你有一个错误。

【讨论】:

  • 好的。我试过:cgh.single_task ([=] () mutable { 但现在我变得很奇怪:在函数std::thread::thread&lt;s_task::task::schedule(std::function&lt;void ()&gt;)::{lambda()#1}&amp;&gt;(s_task::task::schedule(std::function&lt;void ()&gt;)::{lambda()#1}&amp;)': top.cpp:(.text._ZNSt6threadC2IRZN6s_task4task8scheduleESt8functionIFvvEEEUlvE_JEEEOT_DpOT0_[_ZNSt6threadC5IRZN6s_task4task8scheduleESt8functionIFvvEEEUlvE_JEEEOT_DpOT0_]+0x30): undefined reference to pthread_create'collect2:错误:ld返回1退出状态
  • 我希望 sdf_write 是 non-const 因为它修改了一些变量。
  • 感谢您的帮助。但我仍然收到最后一个错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多