xamid
xamid

Reputation: 493

Understanding of function pointer syntax in c++

I have two questions

  1. Are both of these declarations of setEvalFunction equivalent for using EvalFunctionPtr = T (*)(const std::vector<T>&);?

    a) void setEvalFunction(const EvalFunctionPtr& evalFunc);
    
    b) void setEvalFunction(T (* const &evalFunc)(const std::vector<T>&));
    
  2. What is the difference between the following parameters (since both seem to work fine).

    a) T (* const &evalFunc)(const std::vector<T>&)
    
    b) T (* const &evalFunc)(const std::vector<T>&)&
    

I want to have something equivalent to 1 a), i.e. passing a reference to a constant function pointer, but without using some extra definition like using EvalFunctionPtr = ....

Upvotes: 1

Views: 115

Answers (1)

eerorika
eerorika

Reputation: 238471

  1. Are both of these declarations of setEvalFunction equivalent

Yes.

  1. What is the difference between the following parameters (since both seem to work fine).

I do believe that 2. b) R (* const & fptr)(/*args*/)& is ill-formed because a (non-member) function pointer cannot have a ref-qualifier, which is what the final & denotes. However, possibly due to a compiler bug, my GCC does accept it and parses it as same as R (* const & fptr)(/*args*/). EDIT: clang correctly refuses to compile it.

I want to have something equivalent to 1 a), i.e. passing a reference to a constant function pointer, but without using some extra definition like using EvalFunctionPtr = ....

That is quite apt description of 1. b).

Passing the value of a function pointer is passing a 64bit integer (in my case of a 64 bit system), which is not the same as passing the reference of a function pointer, since the reference is applied by the compiler, and takes zero time during runtime. But the copy of an integer takes time, doesn't it?

Passing a reference doesn't take zero time during runtime. In fact, passing a reference argument to a function is practically copying the (probably 64 bit in your case) address of the pointer and dereferencing it (assuming you actually access the reference), which is more than just copying in the case of passing the pointer by value. If the function was expanded inline by the optimizer, then there is probably no difference either way.

Upvotes: 1

Related Questions