我正在查看这个简单的结构:
struct Journal
{
std::string title;
std::vector<std::string> entries;
explicit Journal (const std::string& title): title(title)
{
std::cout << "Address of title is " << &title << std::endl;
}
void add(const std::string& entry)
{
std::cout << "Address of title is " << &title << std::endl;
entries.push_back(entry);
}
};
int main() {
std::string title = "Hello";
std::string entry = "World";
std::cout << "Address of title is " << &title << std::endl;
Journal *journal = new Journal(title);
(*journal).add(entry);
std::cout << journal->entries.front() << std::endl;
return 0;
}
我一直认为 title 的地址在整个执行过程中应该是相同的,但是,我得到了以下输出结果是错误的:
Address of title is 0x7ffee90d3978
Address of title is 0x7ffee90d3978
Address of title is 0x7fa86f402740
World
有人能解释一下初始化后发生了什么吗?为什么我会得到不同的地址?这是否意味着发生了副本?
struct Journal
{
std::string title;
这title
与title
您在 main() 中的不同,因此地址会有所不同。
explicit Journal (const std::string& title): title(title)
{
std::cout << "Address of title is " << &title << std::endl;
这里你打印的是title
参数的地址而不是成员的地址title
,所以它和main()
. 该成员title
具有不同的地址,您在致电时会看到该地址add()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句