c++ - C++ 指针的示例用法是什么?

标签 c++ pointers

我正在自学 C++,我了解指针的工作原理。但是我使用的文档非常直白,示例并没有真正说明为什么或何时使用指针。几个真实世界的例子将帮助我记住知识。

最佳答案

当您希望您的对象存在的时间比当前堆栈长时,您可以使用指针。您还可以使用它们来避免将对象复制到容器中。

// TODO: Remember to call DeleteObjects() when you're done here!!
std::vector<MyObject*> Objects;

void Test()
{
    MyObject *const pObject = new MyObject();
    Objects.push_back(pObject);
}

void DeleteObjects()
{
    std::vector<MyObject*>::iterator it = Objects.begin(), itEnd = Objects.end();
    for (; it != itEnd; ++it)
    {
        delete *it;
    }
    Objects.clear();
}

关于c++ - C++ 指针的示例用法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3164792/

相关文章:

c++ - 是否可以在C++中创建指向类的指针

c++ - 没有元组的 Variadics 模板

c++ - 此警告与枚举类大小有关吗?

c - float arrayName[][] 和 float (* arrayNamePointer)[] 有什么区别

void* 指针的 C++ 替代品(不是模板)

c++ - 为什么下面的数组解引用指针具有相同的值 : the pointer to an array, ?

c - 使用 memcpy 从数组转换为 int

c++ - 递归函数中的段错误

c++ - 从 CFURLRef 或 CFStringRef 转换为 std::string

c++ - 使用 C++ 和 Jsoncpp 解析 youtube 数据