I am trying to understand the below code snippet
template <typename T>
class testopaque {
public:
void test(T var = T()) {}
};
How does the default argument work when called with a pointer type example int *
int main() {
testopaque<int *> obj1;
obj1.test();
}
what would the compiler generate when obj1.test() is called. I get a compiler error when I try
int main() {
int * var = int *();
}
error: expected primary-expression before ‘int’
int * ptr = int *();
CodePudding user response:
This is an example of how C 's complicated syntax and grammar just produces unexpected results:
int *();
Your C compiler is very tempted to interpret this construct as a "function returning a pointer to an int
". Your C compiler gives in to this temptation, with the observed results.
You need to teach your C compiler what you're trying to accomplish here:
typedef int *intp;
int main()
{
int * var = intp();
}
CodePudding user response:
Suppose you have x=1 2
. Would you expect x*3
, which is 9, to equal 1 2*3
, which is 7?
A similar problem is happening here. int*()
isn't the same as T=int*
then T()
.
Try (int*){}
, which solves the combined parsing and precident problems. Or using T=int*; int* x=T();
, or even int*x={};
.
CodePudding user response:
When you use an expression like:
T var = T();
Where T
is a pointer type then var
will be assigned nullptr