在临时对象上调用成员函数时生成警告 [英] Generating a warning when a member function is invoked on a temporary object

查看:59
本文介绍了在临时对象上调用成员函数时生成警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定矩阵模板类mat<M,N,T>,下面的成员函数允许我高效地转置行向量或列向量,因为它们具有相同/相应的内存占用:

template<int M, int N=M, typename T = double>
struct mat {
    // ...
    template<int Md = M, int Nd = N, typename = std::enable_if_t<Md == 1 || Nd == 1>>
    const mat<N, M, T>& transposedView() const {
        static_assert(M == 1 || N == 1, "transposedView() supports only vectors, not general matrices.");
        return *reinterpret_cast<const mat<N, M, T>*>(this);
    }
}

我多年来一直使用此函数,出于习惯,开始在临时表达式(/*vector-valued expression*/).transposedView()上调用它,忘了它会返回对临时表达式的引用,导致未定义的行为,GCC就是这样咬我的。

是否有简单的方法可以添加在临时调用时会生成某种警告的内容?

或者,只要我不存储引用,在临时上调用它实际上就应该是安全的吗?

推荐答案

成员函数可以是qualified for lvalue or rvalue objects。使用它,您可以创建一个重载集,如

template<int M, int N=M, typename T = double>
struct mat {
    // ...
    template<int Md = M, int Nd = N, typename = std::enable_if_t<Md == 1 || Nd == 1>>
    const mat<N, M, T>& transposedView() & const {
        static_assert(M == 1 || N == 1, "transposedView() supports only vectors, not general matrices.");
        return *reinterpret_cast<const mat<N, M, T>*>(this);
    }
    template<int Md = M, int Nd = N, typename = std::enable_if_t<Md == 1 || Nd == 1>>
    const mat<N, M, T>& transposedView() && const = delete;
}

现在,如果尝试使用rvalue对象调用函数,将出现编译器错误。

这篇关于在临时对象上调用成员函数时生成警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆