私はSTDコンテナに収納参照について、別のSOの記事でこのコメントに出くわした:それは、C++言語の欠陥だ保存参照GNU C++ 98
。 参照のアドレスを取得することはできません。その場合、参照するオブジェクトが のアドレスになり、参照先へのポインタが決して得られません。 std :: vectorはその要素へのポインタで動作するので、格納されている値は である必要があります。代わりに ポインタを使用する必要があります。
ポストに:私の次のコードは動作しますなぜこれが正しいと仮定すると
Why can't I make a vector of references?
、誰かが説明できますか?私は人が間違っていることを暗示しようとしていない、私は可能なものとできないものを理解するように努力している。
マイコード:
#include <iostream>
#include <vector>
#include "stdio.h"
struct TestStruct
{
int x;
int y;
};
class TestClass {
public:
TestClass(int x, int y);
int getX();
int getY();
private:
int mX;
int mY;
};
TestClass::TestClass(int x, int y)
{
mX = x;
mY = y;
}
int TestClass::getX()
{
return mX;
}
int TestClass::getY()
{
return mY;
}
int main()
{
// test struct
std::vector<TestStruct> structVec;
TestStruct testStruct;
testStruct.x = 10;
testStruct.y = 100;
structVec.push_back(testStruct);
testStruct.x = 2;
testStruct.y = 200;
structVec.push_back(testStruct);
testStruct.x = 3;
testStruct.y = 300;
structVec.push_back(testStruct);
for (int i = 0; i < structVec.size(); i++)
{
printf("testStruct [%d] - [x: %d, y: %d] \n", i, structVec[i].x, structVec[i].y);
}
// test object
std::vector<TestClass> objVec;
objVec.push_back(*new TestClass(10, 100));
objVec.push_back(*new TestClass(20, 200));
objVec.push_back(*new TestClass(30, 300));
for (int i = 0; i < objVec.size(); i++)
{
printf("objVec [%d] - [x: %d, y: %d] \n", i, objVec[i].getX(), objVec[i].getY());
}
}
出力:
testStruct [0] - [x: 10, y: 100]
testStruct [1] - [x: 2, y: 200]
testStruct [2] - [x: 3, y: 300]
objVec [0] - [x: 10, y: 100]
objVec [1] - [x: 20, y: 200]
objVec [2] - [x: 30, y: 300]
あなたのコードに参照の 'vector'がありません。メモリリークがありました. – krzaq
引用符は部分的に" std :: vectorはその要素へのポインタで動作します " –