【发布时间】:2020-09-19 20:29:14
【问题描述】:
第一段代码不能编译,而第二段代码可以。为什么?
代码确实几乎相同。 如果能在这个问题上得到一些帮助,我将不胜感激。
下面的代码无法编译。您可以在http://cpp.sh/8j53y 上查看。
dynamic_cast
#include <iostream>
#include <memory>
using namespace std;
class Derived;
class Base {
public:
static unique_ptr<Base>& get_instance()
{
pBase = make_unique<Derived>();
return pBase;
}
private:
static unique_ptr<Base> pBase;
};
class Derived: public Base { };
std::unique_ptr<Base> Base::pBase = nullptr;
int main () {
auto& instance = Base::get_instance();
return 0;
}
下面的代码可以编译。
#include <iostream>
#include <memory>
using namespace std;
class Derived;
class Base {
public:
static unique_ptr<Base>& get_instance();
private:
static unique_ptr<Base> pBase;
};
class Derived: public Base { };
std::unique_ptr<Base> Base::pBase = nullptr;
unique_ptr<Base>& Base::get_instance()
{
pBase = make_unique<Derived>();
return pBase;
}
int main () {
auto& instance = Base::get_instance();
return 0;
}
【问题讨论】:
-
我假设
auto Base::get_instance();应该是auto instance = Base::get_instance();- 不是它会编译,但问题不会是与错字相关的问题 -
这很重要。链接过时了,我个人一开始就无法打开您的链接。一个问题必须是自包含的。它必须包含您询问的正确代码,没有其他问题(以及错误消息)。您正在请求志愿者来帮助您。不要轻率地对待他们的时间。
-
很抱歉打扰您。我会听从您的建议。今天的网站有些不稳定。
-
旁白:将你的单身人士放在
unique_ptr中有什么意义?您真的打算让调用者能够重置该指针吗? -
这只是整个项目的一部分。我部分同意你的观点。我们假设调用者不会重置那个指针,那么真的没有必要使用
unique_ptr吗?
标签: c++ c++11 inheritance c++17 unique-ptr