Constructor not returning usable object

一曲冷凌霜 提交于 2019-12-04 11:15:26

问题


I have a problem with the constructor, which is not working as I'd expect.

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

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

However, if I try to build a class like below (which should be equivalent) the results are quite unexpected. There is no error message/warning when compiling or running the program. But if you try to use this variable a somewhere and call its methods (for example a.doSomething()), it will crash.

I put some 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 am wondering why this is happening? Is the 2nd declaration illegal?

EDIT: I will post some code of the class

template <int x>
class MyClass {
public:
    vector<float> v;
    MyClass<x>(vector<float> v1) {
      v = v1;
    }

};

回答1:


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

This is not a variable declaration. It is the declaration of a function named a that returns a MyClass<2> object and takes as an argument a "pointer to a function that takes no arguments and returns a vector<float>." Confusing? Yes. This is what is referred to as the "most vexing parse."

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 isn't explicit, you could use:

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

(Though, unless you mean for 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 sort of thing. Visual C++ warns:

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

Clang warns:

warning: parentheses were disambiguated as a function declarator

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


来源:https://stackoverflow.com/questions/5363748/constructor-not-returning-usable-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!