c++ - 使用非常量值初始化的对 const 类成员的引用

标签 c++ c++11 const-reference

我有一个类,作为它的输入数据,要么使用对外部数据的引用(不复制),要么根据其他输入创建数据本身。我更喜欢使用引用(以避免取消引用,因为数据是矩阵)并以以下结构(简化)结束:

#include <iostream>
#include <vector>
using namespace std;
using VectI = vector<int>;

class A {
    VectI x0;
    VectI const & x = x0;
public:
    A(VectI const & extX) : x(extX) {}     // referencing existing external data
    A(int i) { x0.push_back(i); x0.push_back(i*i); }   // create from other data
    void show_x()
        { cout << "x ="; for (auto&& i : x) cout << " " << i; cout << endl; }
};

int main() {
    VectI myX = {1, 2, 3};
    A a(myX); a.show_x(); // a references myX
    A b(2); b.show_x();   // b creates its own data based on i=2
    return 0;
}

示例有效:

x = 1 2 3
x = 2 4

但是这种方法有什么潜在的问题吗? 特别是,我正在更改由 const vector x“合法”C++ 引用的 x0,或者它是什么其他编译器可能会提示?

此外,我可以确定第一个构造函数避免复制数据吗?

最佳答案

这在 C++11 标准中很好,但您的代码非常脆弱。

特别是编译器生成的复制和移动构造函数以及赋值运算符将无法正常工作,因此您必须构建自己的。

您可能还会遇到悬挂引用:请记住,由于 const 引用而导致的对象生命周期延长是不可传递的。将 A(VectI const & extX) 与匿名临时文件一起使用的行为未定义。

使用指向 VectI 的指针 - 也许甚至是指向 VectIstd::unique_ptr 以及所有权的概念可能更安全路要走。

关于c++ - 使用非常量值初始化的对 const 类成员的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34744762/

相关文章:

C++ 模板 : typename and function to map to int

c++函数的返回类型是其输入的函数

c++ - 为什么让 operator new 私有(private)中断 std::shared_ptr?

c++ - 通过 const 引用延长临时生命周期

c++ - const 引用类成员是否会延长临时对象的生命周期?

c++ - 隐式转换 : const reference vs non-const reference vs non-reference

c++ - C++ 中用于国际象棋移动生成的动态存储

c++ STL按int和string的 vector 排序

c++ - 该声明的含义 count[array[i]]

C++ 11 多线程合并排序错误 “no instance of contructor ' std::thread' 匹配参数列表”