[英]reference-to-cont class member initialized with non-const value
I have a class that should, as its input data, either use a reference to external data (without copying), or create the data itself based on other input. 我有一类应该作为对它的输入数据的类,或者使用对外部数据的引用(无复制),或者根据其他输入创建数据本身。 I prefer using references (to avoid dereferencing, since the data are matrices) and ended up with the following structure (simplified): 我更喜欢使用引用(避免取消引用,因为数据是矩阵)并且最终具有以下结构(简化):
#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;
}
The example works: 该示例工作:
x = 1 2 3
x = 2 4
but are there any potential problems with this approach? 但是这种方法有潜在的问题吗? In particular, is the fact that I am changing x0
that is referenced by the const vector x
'legal' C++, or is it something that other compilers might complain about? 特别是我正在更改const向量x
'合法'C ++引用的x0
的事实,还是其他编译器可能会抱怨的事情?
Also, can I be sure that the first constructor avoids copying data? 另外,我可以确定第一个构造函数避免复制数据吗?
This is fine in the C++11 standard but your code is very brittle. 这在C ++ 11标准中很好,但是您的代码非常脆弱。
In particular the compiler generated copy and move constructors and the assignment operator will not work correctly, so you'll have to build your own. 特别是编译器生成的copy和move构造函数以及赋值运算符将无法正常工作,因此您必须构建自己的。
You might also encounter dangling references: remember that the object lifetime extension due to a const reference is not transitive. 您可能还会遇到悬空的引用:请记住,由于const引用导致的对象生存期延长不是传递性的。 The behaviour on using A(VectI const & extX)
with an anonymous temporary is undefined. 未将A(VectI const & extX)
与匿名临时使用结合使用的行为。
Using a pointer to VectI
- perhaps even a std::unique_ptr
to a VectI
along with a concept of ownership might be a safer way to go. 使用指针VectI
-甚至一个std::unique_ptr
到VectI
与所有权的概念以及可能会去一个更安全的方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.