0

From Cppreference, I found it noted that

Pointers to data members are Callable, even though no function calls take place.

However, when I test following code

#include <iostream>
#include <functional>
using namespace std;
class CTest
{
public:
    CTest() : n(0) {}
    ~CTest() {}
public:
    int n;
};

int main() {
    CTest o;
    auto f = std::bind(&CTest::n, o);
    f(1) = 2;
    cout << f() << endl;
    return 0;
}

I found that I can call f with any arguments, not limited by count or type.

So, why can I insert almost any thing into f(...)? Is the syntax like

template<class... Args>
int f(Args&&... args) {
    return *pointer_to_data;
}
  • 1
    *the demangle function is just to see what the lambda is* `f` is not a lamda. – 273K Jun 03 '22 at 04:24
  • 1
    *the result became very strange* - the result is not strange, since you bind with the unitialized `CTest::n`. – 273K Jun 03 '22 at 04:37
  • *I think 0 is because default initialization* - 0 is also random, default initialization is not zero initialization. – 273K Jun 03 '22 at 04:42
  • *Why can I insert almost any thing into f(...)?* - not almost any thing. Only [if N == 1 and f is a pointer to data member of class T](https://en.cppreference.com/w/cpp/named_req/Callable) - `f(1)` is `(o_copy).*(&CTest::n);` - just getting reference to `o_copy.n`. – 273K Jun 03 '22 at 04:59
  • I honestly have problems following your description of what is happening. Also, it's unclear what is you observation, what is your interpretation and what you would expect. In any case, reading the uninitialized `o.n` is UB, so you may want to fix that first. As a new user here, also read [ask] and take the [tour]. – Ulrich Eckhardt Jun 03 '22 at 05:18
  • @273K However, I tried to call `f` with 2 arguments like `f(string, int)` or even 3 arguments, it all works, so I think maybe it is a template? – dragon-archer Jun 03 '22 at 05:23
  • @UlrichEckhardt sorry, I changed the code to assign an value in `CTest::CTest()`, and the output is normal, but I am confused with why I can call `f` with any arguments, instead of fixed type and count, is it a template? – dragon-archer Jun 03 '22 at 05:30
  • @273K, I reviewed cppreference, and it noted "Pointers to data members are Callable, even though no function calls take place.", so I can emplace any arguments here is because it actually didn't do anything? But then what is the syntax of `f`? – dragon-archer Jun 03 '22 at 05:49
  • *However, I tried to call f with 2 arguments like f(string, int) or even 3 arguments*. All arguments are ignored. `void func() {}; int main() { auto f = std::bind(func); f(1, "str", std::string()); }` is compiled. – 273K Jun 03 '22 at 06:40

0 Answers0