struct初始化后的不同地址

时间:2018-02-26 03:53:11

标签: c++ c++11

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

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

我一直认为标题的地址在整个执行过程中应该是相同的,但是,我错了,因为我得到了以下输出:

Address of title is 0x7ffee90d3978
Address of title is 0x7ffee90d3978
Address of title is 0x7fa86f402740
World

有人可以解释初始化后发生了什么吗?为什么我会得到一个不同的地址?这是否意味着副本发生了?

1 个答案:

答案 0 :(得分:1)

public class AccessUsers_Extension : PXGraphExtension<AccessUsers>
{
    public PXSelect<Company> Companies;

    public delegate void PersistDelegate();
    [PXOverride]
    public void Persist(PersistDelegate baseMethod)
    {
        foreach (Company company in Companies.Cache.Inserted)
        {
            CompanyExt ordExt = PXCache<Company>.GetExtension<CompanyExt>(company);
            if ((bool)ordExt.UsrSelected)
            {
                using (PXLoginScope ls = new PXLoginScope(PXAccess.GetUserName() + "@" + company.CompanyKey))
                {
                    AccessUsers ac = PXGraph.CreateInstance<AccessUsers>();
                    ac.Caches = Base.Caches;
                    ac.Actions.PressSave();

                    if (ls != null)
                    {
                        ((IDisposable)ls).Dispose();
                        PXDatabase.ResetCredentials();
                    }
                }
            }
        }
    }
}

struct Journal { std::string title; 与main()中的title不同,因此地址会有所不同。

title

您在此处打印的explicit Journal (const std::string& title): title(title) { std::cout << "Address of title is " << &title << std::endl; 参数的地址不是成员title的地址,因此它与title中的地址相同。会员main()具有您在致电title

时看到的不同地址