静态矢量的Getter

Getter for static vector

本文关键字:Getter 静态      更新时间:2023-10-16

我有一个可以工作的类。但当我为它添加静态向量和getter时,我遇到了编译错误。

这里有一个例子:

// 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;
}

怎么了?

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

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

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

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

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();
//                              ^^^^^^