复制琐碎类型的省略号,GCC 中的错误?

问题描述

我正在用带有复制省略的平凡类型做一些测试。正如我之前的问题:Copy elision and trivially copyable types

以下代码适用于 std::string,但不适用于 const char*。 Valgrind 返回我“使用大小为 8 的未初始化值。

#include <iostream>
#include <string>

template <typename T> struct Object {
private:
  T obj = "My name is John Doe and I am an handsome beautiful guy of 178 years "
          "old loullll !!!";

public:
  T *ptr;

  Object() { ptr = &obj; }
};

Object<const char *> f1() { return {}; }

Object<std::string> f2() { return {}; }

int main() {
  {
    auto x = f2();
    std::cout << *x.ptr << std::endl;
  }

  {
    auto x = f1();
    std::cout << *x.ptr << std::endl;
  }
}

由于复制省略应该在两种情况下都发生,我不明白为什么它不适用于这两种情况...

然而,使用对象的这个定义会使事情正常工作(因为我认为,对象变得不可平凡复制)

template <typename T> struct Object {
private:
  T obj = "My name is John Doe and I am an handsome beautiful guy of 178 years "
          "old loullll !!!";

public:
  T *ptr;

// notice the destructor
  ~Object() {}
  Object() { ptr = &obj; }
};

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)