Error invalid use of non static member function thread

I have error: invalid use of non-static member function when I try to compile following code: int main() { data d; cta ce; pthread_t thread1; pthread_t thread2; pthread_create...

I have error: invalid use of non-static member function when I try to compile following code:

int main()
{
    data d;
    cta ce;
    pthread_t thread1;
    pthread_t thread2;
    pthread_create( &thread1, NULL, d.subscribe, NULL ); 
    pthread_create( &thread2, NULL, ce.startStrategy, NULL ); 
    pthread_join(thread1,NULL);
    pthread_join(thread2,NULL);

    return 0;
}

// cta.cpp
// ...
static void* cta::startStrategy()
{
    std::cout<<"haha"<<std::endl;
}

// data.cpp
// ...
static void* data::subscribe()
{ 
  std::cout<<"haha"<<std::endl;
}

getting error:

main.cpp:38:52: error: invalid use of non-static member function
pthread_create( &thread1, NULL, d.subscribe, NULL ); 
                                                ^
main.cpp:39:60: error: invalid use of non-static member function
pthread_create( &thread2, NULL, ce.startStrategy, NULL ); 

however, a similar code snippet works pretty well:

#include <iostream>
#include <pthread.h>
  class Foo {
    public:
      static void func() {
        std::cout << "hi" << std::endl;
      }
  };

  int main() {
    Foo ins;
    pthread_t pt;
    pthread_t pt1;
    pthread_create( &pt, NULL, ins.func, NULL );
    pthread_create( &pt1, NULL, ins.func, NULL );
    pthread_join(pt, NULL);
    pthread_join(pt1, NULL);
    return 0;
  }

it compile fine and prints «hi» twice, i wonder what could be wrong with my code, since I already changed from void to static void and follow the same pattern, why am I still getting non-static error?

MaxFilippov

1 / 1 / 0

Регистрация: 26.03.2017

Сообщений: 50

1

05.05.2017, 19:25. Показов 15922. Ответов 2

Метки нет (Все метки)


C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
 
 
using namespace std;
 
class fraction
{
    
    fraction(double var_sum)
    { 
        
        
        var_sum=m+n;
        var_sum=m-n;
        var_sum=m/m;
        var_sum=m*n;
        
    }
    
    private:
 
    double m,n;
    public:
    
    double var_sum;
     double setdata(double var_sum );
     fraction() {}
};  
double fraction::setdata(double sum_d)
    {
        
        
        sum_d=var_sum;
        
        return  sum_d;
    }
 
 
int  main()
{
    double a;
    cin>>a;
    fraction work;
    cout<<work.setdata<<endl;//Здесь выдает ошибку
    
         return 0;
     }

Ошибка:invalid use of non-static member function

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Hitoku

1754 / 1346 / 1407

Регистрация: 28.10.2016

Сообщений: 4,267

05.05.2017, 19:40

2

Попробуйте так

C++
44
cout << work.setdata(a) << endl;

Добавлено через 1 минуту
Функция же объявлена с параметром, но вы его не передаёте



1



1 / 1 / 0

Регистрация: 26.03.2017

Сообщений: 50

05.05.2017, 19:43

 [ТС]

3

Спасибо,что-то затупил)



0



  • Forum
  • General C++ Programming
  • what cause invalid usage of non-static m

what cause invalid usage of non-static member function

This is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include <iostream>
#include <chrono>
#include <thread>
#include <stdlib.h>
using namespace std;

int absolute(int);

class Data{
public:
	Data(int);
	~Data();
	int length();
	int operator[](int);
private:
	int *answer;
	int answerLength;
	void read_data(int*, int);
	void wait();
};

int main(){
	int n;
	cin >> n;
	Data data = Data(n);
	for(int i = 0; i < data.length(); i++){
		cout << data[i] << " ";
	}
	system("pause");
	return 0;
}

Data::Data(int one){
	int length = one;
	int *data = new int[length];
	for(int i = 0; i < length; i++){
		*(data+i) = 100000000;
	}
	thread first(read_data, data, length);
	thread later(wait);
	later.join();
	first.detach();
	first.~thread();
	int smallest = absolute(*(data+1) - *(data+0));
	int smallest_number = 0;
	for(int i = 0; i < length && *(data+i) != 100000000; i++){
		for(int j = i + 1; j < length && *(data+j) != 100000000; j++){
			if(absolute(*(data+i) - *(data+j)) < smallest){
				smallest = absolute(*(data+i) - *(data+j));
				smallest_number = 1;
			}else if(absolute(*(data+i) - *(data+j)) == smallest){
				smallest_number ++;
			}
		}
	}
	answerLength = 2 * smallest_number;
	answer = new int[2 * smallest_number];
	int location_one = 0;
	for(int i = 0; i < length && *(data+i) != 100000000; i++){
		for(int j = i + 1; j < length && *(data+j) != 100000000; j++){
			if(absolute(*(data+i) - *(data+j)) == smallest){
				*(answer+location_one) = *(data+i);
				location_one ++;
				*(answer+location_one) = *(data+j);
				location_one ++;
			}
		}
	}
}

int Data::operator[](int one){
	if(one < answerLength){
		return *(answer+one);
	}
	return -1;
}

Data::~Data(){
	delete [] answer;
}

int Data::length(){
	return answerLength;
} 
int absolute(int a){
	if(a >= 0){
		return a;
	}else{
		return a * -1;
	}
	return -1;
}

void Data::read_data(int *data, int length){
	for(int i = 0; i < length; i++){
		cin >> *(data+i);
	}
}

void Data::wait(){
	this_thread::sleep_for(chrono::milliseconds(500));
}

And i got this message from compiler:

1
2
3
main.cpp:39:38: error: invalid use of non-static member function

main.cpp:40:19: error: invalid use of non-static member function

Why i cant use member function read_data and wait in a contructor Data::Data().
In order to examinate this problem. I write another program to test.
This is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <stdlib.h>
using namespace std;

class class_one{
public:
	class_one(int);
	~class_one();
private:
	int data_one;
	void function_one(int);
};

int main(){
	int one = 0;
	class_one two(one);
	system("pause");
	return 0;
}

class_one::class_one(int one){
	data_one = one;
	cout << "the object construct with ";
	function_one(data_one);
	
}

class_one::~class_one(){
	
}

void class_one::function_one(int one){
	cout << one;
}

It worked successfully when i used a non-static member function class_one::function_one in constructor class_one::class_one, and show the object construct with 0 on the screen.
I dont know what cause invaid usage of non-static member function.

Last edited on

The syntax for member functions is different since the compiler needs to know whether you mean member variables or not. Plus you need to provide the this pointer:

1
2
	thread first(&Data::read_data, this, data, length);
	thread later(&Data::wait, this);

why cant i just do that?

1
2
thread first(this->read_data, data, length);
thread later(this->wait);

The functions were declared in class, and were called in constructor.
and what different are between thread first(&Data::read_data, this, data, length); and thread first(this->read_data, data, length);?

Last edited on

The first argument that you pass to the thread constructor is a function pointer.

In this case it’s a pointer to a member function so you also need to pass a pointer to the object that the function should be called on (it doesn’t make sense to call a member function without an object) and that is why you pass this (which is a pointer to the current object) as a second argument.

I cannot answer why you have to write exactly &Data::read_data to get a pointer to the function. I guess they could have allowed this->read_data (or perhaps &this->read_data) but it wouldn’t really add much because, no matter which Data object you used in that expression, you would always get the same function pointer.

Also, don’t call the thread destructors explicitly. It will be called automatically when the thread object goes out of scope.

It is almost always wrong to call destructors explicitly. It’s mainly used in combination with placement new, which is something that most people never, or very rarely, use.

Last edited on

and were called in constructor.

It is not called in the class Data. It is called withing the construction of thread. You can’t tell how it is called.

what different are between

The first is correct syntax the latter not.

A construct like &Data::read_data tells the compiler that read_data is a member function of the class Data. It is very well possible that a free function with that name exists.
The special trait of a member function is that the pointer to the object is the first implicitely/[invisibly] passed parameter hence the first parameter in your case is this.

Thus
this->read_data(data, length);
is really
read_data(this, data, length);

Therefore you need to create a function object (for the thread) like i showed.

Can i actually use read_data(this, data, length); instead of this->read_data(data, length); in my programming? since this->read_data(data, length); is really read_data(this, data, length); And can i use thread first(Data::read_data, this, data, length); instead of using an address?

Last edited on

Did you try it? It’s all about what syntax c++ allows and what not.

Why would you want that?

Last edited on

ok thank you coder777 Peter87

Last edited on

Topic archived. No new replies allowed.

У меня ошибка: неверное использование нестатической функции-члена, когда я пытаюсь скомпилировать следующий код:

int main()
{
data d;
cta ce;
pthread_t thread1;
pthread_t thread2;
pthread_create( &thread1, NULL, d.subscribe, NULL );
pthread_create( &thread2, NULL, ce.startStrategy, NULL );
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);

return 0;
}

// cta.cpp
// ...
static void* cta::startStrategy()
{
std::cout<<"haha"<<std::endl;
}

// data.cpp
// ...
static void* data::subscribe()
{
std::cout<<"haha"<<std::endl;
}

получить ошибку:

main.cpp:38:52: error: invalid use of non-static member function
pthread_create( &thread1, NULL, d.subscribe, NULL );
^
main.cpp:39:60: error: invalid use of non-static member function
pthread_create( &thread2, NULL, ce.startStrategy, NULL );

однако подобный фрагмент кода работает довольно хорошо:

#include <iostream>
#include <pthread.h>
class Foo {
public:
static void func() {
std::cout << "hi" << std::endl;
}
};

int main() {
Foo ins;
pthread_t pt;
pthread_t pt1;
pthread_create( &pt, NULL, ins.func, NULL );
pthread_create( &pt1, NULL, ins.func, NULL );
pthread_join(pt, NULL);
pthread_join(pt1, NULL);
return 0;
}

он хорошо компилируется и печатает «привет» дважды, мне интересно, что может быть не так с моим кодом, так как я уже перешел с void на static void и следую той же схеме, почему я все еще получаю нестатическую ошибку?

-1

Решение

Прежде всего, не используйте pthread, Используйте C ++ std::threadи достичь счастья.

Посмотрите это:

std::thread t1(&data::subscribe, &d);
std::thread t2(&cta::start_strategy, &ce);

Во-вторых, наиболее вероятной причиной вашей проблемы является то, что static Модификатор должен использоваться в определении класса (файл .h), а не в определении функции вне класса.

1

Другие решения

Если вы собираетесь использовать pthread_create, вы должны передать ему параметры, которые он хочет. Начальная процедура void *(*start_routine) (void *), Обратите внимание, что там нет ничего о какой-либо функции-члена, static или иным образом. Поэтому код неверен, даже если он работает на какой-то платформе.

-1

I initially thought the problem to be the usage of std::reference_wrapper. But the compilation error is actually due to the class member function needing to be a pointer. The following compiles with gcc 7.3.1:

#include <thread>
#include <utility>
#include <functional>

class x {
public:

    void start_thread();
};

int main()
{
    x y;

    std::thread thr{&x::start_thread, std::ref(y)};
}

The usual approach to launching a thread for a class member is to pass a plain pointer as the class instance. This works too, in this case:

std::thread thr{&x::start_thread, &y};

And this is the more common syntax. The reference wrapper is not really needed. But in all cases the first parameter must be a pointer to a class method. &x::start_thread is such a pointer. x::start_thread itself isn’t. That’s the real problem.

The parameter to std::thread‘s constructor is specified merely as…

f — Callable object to execute in the new thread

You have to really dig into the definition of a callable object. The basic usage that I had in mind corresponds to the third option listed there for a callable object. But a reference wrapper is also acceptable. However, in all cases you have to have a pointer to a member function as the first argument.

Hello,
I am trying to call a function call_from_thread_description from another function inside a class and I am getting the following error. I can’t find the right to add a function to the pool.

Error: /home/hani/workspace/transform/Transform.cpp:127:104: error: invalid use of non-static member functiondr esults.push_back(thread_pool.push(Transform::call_from_thread_description, data[i], data[j], res));

void Transform::call_from_thread_description(const vector<string> & e1, const <string> & e2, <string>  & res)
{ 
//DO SOMETHING HERE
}
void Transform::computer_intersection()
{
    vector<string> res;
    int Num_Threads =  thread::hardware_concurrency();
    ctpl::thread_pool thread_pool(Num_Threads);
    for(int i = 0; i < data.size();i++)
    {
        data_sets tmp;
        for(int j = 0; j < data.size();j++)
        {
            results.push_back(thread_pool.push(call_from_thread_description, data[i], data[j], res));
            if(j % Num_Threads == 0 || j == data.size() -1)
            {
               results.clear();
            }
       }
  }
}

Понравилась статья? Поделить с друзьями:
  • Error invalid use of incomplete type
  • Error invalid url unable to find install package
  • Error invalid type argument of unary have int
  • Error invalid type argument of unary have float
  • Error invalid transaction termination