g++ treats returned string literal as const char pointer not const char array

旧巷老猫 提交于 2019-11-28 09:12:00

It appears that this is a bug affecting several versions of gcc which has been reported over and over again, most recently about a month ago against the most recent version, 4.8.2. See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=24666

If you want a reusable C++03 workaround (i.e. one in which you won't have to care about what the return type is, as long it is constructible from a char array), you will have to use some kind of a char array wrapper.

template <size_t N>
struct char_array_ref
{
    typedef const char (&ref_type)[N];
    ref_type ref;

    template <typename T>
    operator T() const
    {
        return T(ref);
    }
};

template <size_t N>
char_array_ref<N> stupid_gxx_use_array_reference(const char (&chars)[N])
{
    return char_array_ref<N> { chars };
}


Test fn()
{
  return stupid_gxx_use_array_reference("foo");
}

Should be easy to regex propagate this across your codebase, too.

Obviously, in your code you can change stupid_gxx_use_array_reference into something less verbose.

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