我在另一篇 SO 帖子中看到了这条评论,关于在 std 容器中存储引用:
It's a flaw in the C++ language. You can't take the address of a reference, since attempting to do so would result in the address of the object being referred to, and thus you can never get a pointer to a reference. std::vector works with pointers to its elements, so the values being stored need to be able to be pointed to. You'll have to use pointers instead.
帖子:
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]
最佳答案
当你写这样的代码时:
objVec.push_back(*new TestClass(10, 100));
您正在创建一个 new
TestClass
的实例在堆上,那么您将使用 *
取消引用它,然后在调用 push_back
时将其复制到 vector 中.
但是你泄露了原来的TestClass
使用 new
分配的对象在堆上。
您可能想要使用 vector<shared_ptr<TestClass>>
或 vector<unique_ptr<TestClass>>
相反,如果您想存储指针(智能 指针)而不是 TestClass
实例(你确定吗?)。
请注意,引用 vector 将为 vector<TestClass&>
, 这是错误的。
P.S. 正如您在标题中引用了 C++98",您不能拥有 unique_ptr
,因为它需要 C++11 移动语义。shared_ptr
成为 C++ 的标准11;您仍然可以在 C++98 中使用 boost::shared_ptr
。
关于c++ - 使用 std::containers 存储引用,gnu c++98,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40005148/