智能指针是否可以分别进行转发声明和初始化?

问题描述 投票:0回答:1

我正在尝试学习如何在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':重新定义;不同的基本类型

c++ pointers unique-ptr
1个回答
0
投票

您可以声明全局或命名空间作用域对象,而无需使用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.
© www.soinside.com 2019 - 2024. All rights reserved.