简体   繁体   中英

Why does this code make the VC++ compiler crash?

I'm using the following compiler:

Microsoft Visual C++ 2010

The following code crashes the compiler when it's compiled:

template<class T_> 
void crasher(T_ a, decltype(*a)* dummy = 0){}

int main()
{
    crasher(0);
    return 0;
}

decltype(*a)* used to enforce T_ to be a pointer-like type - such as char* , int* , and shared_ptr<int> .

Why is it crashing? Is this a known bug?

Assuming your goal is

decltype(*a)* used to enforce T_ to be a pointer-like type - such as char* , int*, and shared_ptr.

... what you need is simple template, not a code which happens to crash the compiler :)

Here is something that may work for you

#include <memory>
#include <iostream>

// uncomment this "catch all" function to make select(0) compile
// int select(...){ return 0;}
template<class T>  int select(T*){ return 1;}
template<class T>  int select(std::auto_ptr<T>){ return 1;}
// add boost::shared_ptr etc, as necessary

int main()
{
    std::cout << select(0) << std::endl;
    std::cout << select(std::auto_ptr<int>()) << std::endl;
    std::cout << select(&std::cout) << std::endl;
    return 0;
}

该模板对于T_=intT_=int无效是因为前缀operator*是替换失败,所以它应该以某种方式失败,尽管当然没有崩溃。

I just dont understand why you write decltype(*a)* instead of decltype(a). Since 0(zero) is int by default, then the expression decltype(a) will be int as well. If you want var dummy be a pointer to decltype(a), then you have to write decltype(a)*. This way, dummy will be of type int*. You have also to consider type conversions. 0 can convert to int*. Not sure it works for all types .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM