Constructor not returning a useful object

I have a problem with a constructor that doesn't work as I expected.

If I try to initialize my class, it will work, and I will get a useful object:

vector<float> v; MyClass<2> a(v); 

However, if I try to build a class similar to the one below (which should be equivalent), the results will be quite unexpected. There is no error / warning message when compiling or starting the program. But if you try to use this variable somewhere and call its methods (e.g. a.doSomething ()), it will work.

I put the code inside the constructor to notify me if it is used. It turned out that no code inside the constructor was actually executed in this case.

 MyClass<2> a(vector<float>()); 

So, I wonder why this is happening? Is the 2nd declaration illegal?

EDIT: I will post some class code

 template <int x> class MyClass { public: vector<float> v; MyClass<x>(vector<float> v1) { v = v1; } }; 
+7
source share
1 answer
 MyClass<2> a(vector<float>()); 

This is not a variable declaration. This is a declaration of a function named a , which returns a MyClass<2> object and takes as argument "a pointer to a function that takes no arguments and returns vector<float> ". Mixing? Yes. This is what is called the "most unpleasant analysis."

You need extra parentheses:

 MyClass<2> a((vector<float>())); ^ ^ 

Or you can use copy initialization:

 MyClass<2> a = MyClass<2>(vector<float>()); 

Or, since your constructor is not explicit , you can use:

 MyClass<2> a = vector<float>(); 

(Although, if you do not want the vector<float> objects to be implicitly convertible to MyClass<N> objects, you probably want to make this constructor explicit .)


A good compiler should warn you about this. Visual C ++ warns:

warning C4930: ' MyClass<x> a(std::vector<_Ty> (__cdecl *)(void)) ': the prototyped function was not called (was the variable defined?)

Klang warns:

warning: parentheses were ambiguous as a function declarator

 MyClass<2> a(vector<float>()); ^~~~~~~~~~~~~~~~~ 
+18
source

All Articles