Reputation: 29
Thank you all for your answers. And thanks for the cppinsight and godbolt, did not know these.
I edited my question here what I want to do. Basically I have a SDK acquisition function that has an pointer float argument as input, and I want to monitor that argument in real time to know the status of the acquisition. Now i got this code to work:
#include <iostream>
template <class T>
class MonitoredVariable
{
public:
MonitoredVariable() {}
// MonitoredVariable(const T& value) : m_value(value) {}
operator T&() { return m_value; }
//operator const T&() const { return m_value; }
MonitoredVariable& operator = (float value)
{
printf("Variable modified\n");
this->m_value = &value;
printf("%f \n", *this->m_value);
return *this;
}
MonitoredVariable& operator * () {return *this;}
private:
T m_value;
};
void SDKfunctionIcannotChange(float *a)
{
*a = (float) 5.2;
printf("%f \n", *a); // if I comment this out, x will not update?!?!
return;
}
int main()
{
MonitoredVariable<float*> x;
*x=0;
SDKfunctionIcannotChange(x);
printf("%f \n", *x);
return 1;
}
But strangely if I comment out that printf
command in the SDKfunctionIcannotChange
function, then the x value will not change. Any ideas why is this happening?
So with printf (correct):
Variable modified
0.000000
5.200000
5.200000
and without
Variable modified
0.000000
0.000000
thanks..
Upvotes: 2
Views: 74
Reputation: 37697
This answers original question before extensive edit.
Basically your program is equivalent to:
int main()
{
float *x = nullptr;
float y = 5;
*x = y; // here is UB since x == nullptr
}
See cppinsights: problematic line looks like this *static_cast<float *>(x.operator float *&()) = y;
. So your code do not use custom operator=
, but conversion operator.
Basically problem is code which uses template.
I do not know what was your intent, maybe this:
#include <iostream>
template <class T>
class MonitoredVariable
{
public:
MonitoredVariable() {}
MonitoredVariable(const T& value) : m_value(value) {}
operator T&() { return m_value; }
operator const T&() const { return m_value; }
MonitoredVariable& operator = (const T& value)
{
printf("Variable modified\n");
m_value = value; // here was also a problem
return *this;
}
int main()
{
MonitoredVariable<float*> x;
float y = 5;
x = &y;
return;
}
Upvotes: 3
Reputation: 10604
The *x
expression calls operator*
with an argument of x
. During the name lookup, a builtin operator*
for pointers is found. Given that your class MonitoredVariable
has a conversion operator to T
(which is a pointer type in your case), that conversion operator is called and the returned pointer, which is null, is then dereferenced causing a crash.
What you probably wanted to write is x = y
.
Upvotes: 1