在临时对象上调用成员函数时生成警告

2022-02-25 00:00:00 c++ c++17 temporary-objects

给定矩阵模板类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对象调用函数,将出现编译器错误。

相关文章