使用std::containers存储引用,gnuc++98

Storing references with std:: containers , gnu c++98

本文关键字:gnuc++98 引用 containers std 使用 存储      更新时间:2023-10-16

我在另一篇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));

在堆上创建TestClassnew实例,然后使用*对其进行解引用,然后在调用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