使用std::containers存储引用,gnuc++98
Storing references with std:: containers , gnu c++98
我在另一篇SO文章中看到了这条关于在std容器中存储引用的评论:
这是C++语言中的一个缺陷。你不能接受引用,因为尝试这样做会导致被引用的对象,因此您永远无法获得指向参考资料。std::vector使用指向其元素的指针,因此存储的值需要能够被指向请改用指针。
帖子:
为什么可以';我不做一个参考向量吗?
假设这是正确的,有人能解释为什么我下面的代码能工作吗?我并不是想暗示这个人错了,我只是想确保我明白什么是可能的,什么是不可能的。
我的代码:
#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));
在堆上创建TestClass
的new
实例,然后使用*
对其进行解引用,然后在调用push_back
时将其复制到向量中。
但是您正在泄漏在堆上使用new
分配的原始TestClass
对象。
如果要存储指针(智能指针(而不是TestClass
实例,则可能需要使用vector<shared_ptr<TestClass>>
或vector<unique_ptr<TestClass>>
(您确定吗?(。
请注意,引用的向量将是vector<TestClass&>
,这是错误的。
p.S.正如您在标题中引用的C++98",您不能使用unique_ptr
,因为它需要C++11移动语义。shared_ptr
与C++11一起成为标准;您仍然可以在C++98中使用boost::shared_ptr
。
相关文章:
- 将对象数组的引用传递给函数
- 什么时候在C++中返回常量引用是个好主意
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 何时在引用或唯一指针上使用移动语义
- 如何在c++中使用引用实现类似python的行为
- 编译C++时未定义的引用
- Ctypes wstring通过引用传递
- c++r值引用应用于函数指针
- 理解c++中的引用
- C++取消引用指针.为什么会发生变化
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 强制转换为引用类型
- 引用一个已擦除类型(void*)的指针
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 具有默认值的引用获取函数
- 什么是自动迭代器引用的 C++98 等效项?
- 使用std::containers存储引用,gnuc++98
- C++98/03引用折叠和cv限定符