C++ 使用std::containers、gnuc+存储引用+;98
我在另一篇关于在std容器中存储引用的SO帖子中看到了这条评论: <>这是C++语言中的一个缺陷。你不能把电话号码记下来 引用,因为尝试这样做会导致 引用的对象,因此您永远无法获得指向的指针 推荐人。vector使用指向其元素的指针,因此 存储的值需要能够被指向。你必须 用指针代替 该职位: 假设这是正确的,有人能解释我下面的代码为什么工作吗?我不是想暗示那个人是错的,我只是想确保我明白什么是可能的,什么是不可能的 我的代码:C++ 使用std::containers、gnuc+存储引用+;98,c++,pointers,vector,reference,C++,Pointers,Vector,Reference,我在另一篇关于在std容器中存储引用的SO帖子中看到了这条评论: 这是C++语言中的一个缺陷。你不能把电话号码记下来 引用,因为尝试这样做会导致 引用的对象,因此您永远无法获得指向的指针 推荐人。vector使用指向其元素的指针,因此 存储的值需要能够被指向。你必须 用指针代替 该职位: 假设这是正确的,有人能解释我下面的代码为什么工作吗?我不是想暗示那个人是错的,我只是想确保我明白什么是可能的,什么是不可能的 我的代码: #include <iostream> #include
#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());
}
}
当您编写这样的代码时: 您正在堆上创建一个
TestClass
的new
实例,然后使用*
解除对它的引用,然后在调用push\u back
时将其复制到向量中
但是您正在泄漏堆上使用new
分配的原始TestClass
对象
如果要存储指针(智能指针)而不是TestClass
实例(是否确定),则可能需要使用vector
或vector
请注意,引用向量将是向量
,这是错误的
p.S.正如您引用的C++98“在标题中,您不能有
唯一的\u ptr
,因为它需要C++11移动语义shared_ptr
成为C++11的标准;您仍然可以在C++98中使用boost::shared\u ptr
。您的代码中没有向量
。你有一个内存泄漏,otoh。因为引用的部分内容是“std::vector使用指向其元素的指针”,这是胡说八道,所以我不会注意它所说的任何其他内容。谢谢!你的第一句话为我澄清了一切。为了确保我理解正确,在我上面的代码中,堆上有3个TestClass对象,堆栈上的objVec中也有这3个TestClass对象的副本,对吗?堆上有三个泄漏,三个安全存储在std::vector中。
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));