struct初始化后地址不同

凯夫盖伊

我正在查看这个简单的结构:

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;

titletitle您在 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] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

如何初始化不同动态分配地址的向量

来自分类Dev

Ruby-初始化后立即修改Struct属性

来自分类Dev

不同的初始化方式

来自分类Dev

指针初始化:地址或值

来自分类Dev

为什么数组大小初始化在类/ struct / ...内部或外部不同?

来自分类Dev

为什么数组大小初始化在类/ struct / ...内部或外部不同?

来自分类Dev

Swift中的struct数组初始化

来自分类Dev

GCC Struct Doublepointer数组初始化

来自分类Dev

初始化std :: array <struct,size>

来自分类Dev

初始化C ++中的struct指针

来自分类Dev

C ++ const struct初始化

来自分类Dev

在struct中初始化数组

来自分类Dev

初始化指向 struct 的指针的指针

来自分类Dev

如何初始化struct char数组?

来自分类Dev

零初始化,静态初始化和价值初始化有何不同?

来自分类Dev

调用了不同的初始化方法

来自分类Dev

多个JSpinners的初始化方式不同

来自分类Dev

不同种类的变量初始化

来自分类Dev

C ++不同的变量初始化

来自分类Dev

初始化与赋值不同吗?

来自分类Dev

不同的int初始化方式

来自分类Dev

不同的初始化,Common Lisp

来自分类Dev

初始化后更改SimpleModal选项

来自分类Dev

初始化AUGraph后的AVAudioSession属性

来自分类Dev

初始化后未绘制CGContext

来自分类Dev

投放后未初始化变量

来自分类Dev

初始化后整数变为0

来自分类Dev

初始化后属性被擦除 - kotlin

来自分类Dev

初始化:静态符号“ myStruct”的地址用于符号“ otherStruct”