静态矢量的吸气剂

时间:2018-07-27 08:20:51

标签: c++ visual-studio static stdvector

我有可以上课的课。但是当我添加静态矢量和吸气剂时,我遇到了编译错误。

这里是一个例子:

// Config.h file
class Config {
    static std::vector<std::string> m_RemoteVideoUrls;
    ...
public:
    static std::vector<std::string> GetRemoteVideoURLs();
};


// Config.cpp file
static std::vector<std::string> m_RemoteVideoUrls = {"some url"};
...
std::vector<std::string> Config::GetRemoteVideoURLs() {
    return m_RemoteVideoUrls;
}

在Visual Studio 2017中进行编译时遇到了这个奇怪的错误

1>config.obj : error LNK2001: unresolved external symbol "private: static class std::vector<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,class std::allocator<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > > > Config::m_RemoteVideoUrls" (?m_RemoteVideoUrls@Config@@0V?$vector@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V?$allocator@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@2@@std@@A)

经过几次实验,我了解到m_RemoteVideoUrls出了点问题。 因为此存根有效:

std::vector<std::string> Config::GetRemoteVideoURLs() {
    return std::vector<std::string>{"a", "b"};// m_RemoteVideoUrls;
}

但这不起作用:

std::vector<std::string> Config::GetRemoteVideoURLs() {
    LoadConfigIfRequired();
    std::vector<std::string> tmp = m_RemoteVideoUrls;
    return std::vector<std::string>{"a", "b"};// m_RemoteVideoUrls;
}

怎么了?

2 个答案:

答案 0 :(得分:5)

static std::vector<std::string> m_RemoteVideoUrls = {"some url"};

只是一个不相关的全局变量,要给静态成员一个定义,它应该是

std::vector<std::string> Config::m_RemoteVideoUrls = {"some url"};

答案 1 :(得分:1)

您声明了一个与静态向量同名的全局向量,但是从未定义过静态向量本身。必须指定向量所属的位置(指定范围):

static std::vector<std::string> Config::m_RemoteVideoUrls = {"some url"};
//                              ^^^^^^^^

实际上,您甚至可以同时拥有两个向量:

static std::vector<std::string> m_RemoteVideoUrls = {"some url"};
static std::vector<std::string> Config::m_RemoteVideoUrls = {"another url"};

何时使用哪个?好吧,取决于您所处的范围:类Config的成员函数使用静态成员,其他类的成员和全局函数使用全局成员(除非您明确指定范围:::m_RVUConfig::m_RVU )。

当然,拥有相同的名字不是一个好主意,只是为了说明...

然后是第二个问题:

您是否真的打算按值返回静态成员(即始终进行复制)?

您可能希望返回参考:

public:
    static std::vector<std::string> const& getRemoteVideoURLs();
    //                              ^^^^^^
相关问题