c++ - 可以单独声明和初始化智能指针吗?

标签 c++ pointers unique-ptr

我正在尝试学习如何在Cpp中使用智能指针,并且遇到了障碍。我想在我的代码的一部分中声明我的变量为unique_ptr,可能是作为类成员或命名空间的一部分,然后在我代码的其他地方初始化/“make_unique”。我已经阅读了很多有关智能指针和不完整类型信息的问题,但是不确定我是否完全理解。这是我阅读的最后一篇资源。 Incomplete types and shared_ptr / unique_ptr

这是我正在尝试的玩具代码。 'v1'可以按预期运行,单行显示。 “v2”是我想要做的工作

std::unique_ptr<glm::vec3>v1 = std::make_unique<glm::vec3>(); //Works as expected
std::unique_ptr<glm::vec3>v2; //Declare a unique_ptr here, but i don't want to allocate any memory for it yet...

//do things i need to do before memory is allocated to v2

v2 = std::make_unique<glm::vec3>(); //...NOW I want to allocate memory for v2 and prepare it to be used

这些是我从VS2017中得到的错误,都涉及我make_unique v2所在的行:

错误C4430:缺少类型说明符-假定为int。注意:C++不支持default-int

错误C2371:'templategl::v2':重新定义;不同的基本类型

编辑:是的,我应该提供一个更好的例子。在创建一个时,我回答了我自己的问题。修改后的代码如下;
#include <memory>
#include <iostream>

struct vec3 {
    vec3() { x = y = z = 1.f; }
    vec3(float val) { x = y = z = val; }
    float x, y, z;
};

//smart pointers in a namespace...
namespace smptrns {
    std::unique_ptr<vec3>v0; //will be init in a namespace function
    std::unique_ptr<vec3>v1 = std::make_unique<vec3>(); //Works as expected
    std::unique_ptr<vec3>v2; //Declare a unique_ptr here, but i don't want to allocate any memory for it yet...
    //v2 = std::make_unique<vec3>(); //...NOW I want to allocate memory for v2 and prepare it to be used
    //^This is my problem, initializing v2 in namespace outside of a function.
    void initpntr() {
        v0 = std::make_unique<vec3>(); //Works
    }
}

int main() {
    smptrns::initpntr();
    smptrns::v2 = std::make_unique<vec3>(5.f); //Also works
    std::cout << smptrns::v0->x << "\t" << smptrns::v1->x << "\t" << smptrns::v2->x << "\n";
}

我试图通过函数的外部初始化v2,方法是通过从 namespace 中的函数或在我的主循环中分配v2并通过::运算符直接访问来进行修复。

最佳答案

您可以声明全局或命名空间范围对象,而无需使用extern关键字对其进行初始化:

extern std::unique_ptr<glm::vec3> v2; // Declaration only.
// ...
std::unique_ptr<glm::vec3> v2 = std::make_unique<glm::vec3>(); // Declaration and definition with initialization.

关于c++ - 可以单独声明和初始化智能指针吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59529859/

相关文章:

c++ - 从函数返回值

c++ - 在 C++ 中链接非重叠、非连续的迭代器 (/boost)

c - GCC - 我应该如何正确格式化这个字符串?段错误

c++ - unique_ptr 交换不起作用

c++ - std::unique_ptr 和指向指针的指针

c++ - 检查单选按钮状态 winapi

c++ - 为什么自动不检测函数的引用类型

c - 模块化编译时数组扩展

C: printf ("%s\n", str) 产生乱码?

c++ - 在 C++11 中将结构作为输出参数传递