[英]Why does this not violate One definition rule?
I am new to c++ and trying to understand the one-definition-rule. 我是c ++的新手,试图理解一定义规则。 Will including the below test.h file in multiple c++ files voilate the one definition rule (syspath and tags). 将以下test.h文件包含在多个c ++文件中将破坏一个定义规则(syspath和标签)。 If not why not ? 如果不是,为什么不呢?
#ifndef TEST_H
#define TEST_H_
#include <string>
#include <unordered_set>
namespace X {
class Test {
public:
// Default constructor.
Test();
~Test();
const std::string& syspath() const { return syspath_; }
const std::unordered_set<std::string> tags() const { return tags_;}
private:
std::string syspath_;
std::unordered_set<std::string> tags_;
};
} // namespace X
#endif // TEST_H_
syspath
and tags
are not objects or non-inline functions, so the ODR does not apply to them. syspath
和tags
不是对象或非内联函数,因此ODR不适用于它们。 The ODR for types applies indirectly to them (as they're part of the type X::Test
), but as long as they (and X::Test
) are identical in every compilation unit, they're fine. 类型的ODR间接应用于它们(因为它们是X::Test
类型的一部分),但是只要它们(和X::Test
)在每个编译单元中都相同,就可以了。
As the wikipedia page notes, there are two related but different parts of the ODR -- one that applies to templates, types, functions and objects within a compilation unit and one that applies to objects and non-inline functions across compilation units. 正如Wikipedia页面所指出的那样,ODR有两个相关但不同的部分-一个适用于编译单元中的模板,类型,函数和对象,另一个适用于整个编译单元中的对象和非内联函数。
ODR allows multiple definitions of a class as well as definitions of inline functions as long as all definitions are the same, and each definition is in a separate translation unit. ODR允许一个类的多个定义以及内联函数的定义,只要所有定义都相同,并且每个定义位于单独的转换单元中即可。 The latter requirement is satisfied by the header guards (or it would be if there wasn't a typo). 后一个要求由标题卫兵来满足(或者如果没有错字,那就应该是)。
A class definition merely declares data members. 类定义仅声明数据成员。 These are not variable definitions. 这些不是变量定义。 ODR allows unlimited declarations. ODR允许无限制的声明。
No instance of a member variable exists until an instance of the class is constructed, and each instance of the class contains a separate instance of the variable. 在构造该类的实例之前,不存在成员变量的实例,并且该类的每个实例都包含变量的单独实例。
There are no violations of ODR if this header is included in multiple translation units. 如果此标头包含在多个转换单元中,则不会违反ODR。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.