首页 > 解决方案 > 复制琐碎类型的省略号,GCC中的错误?

问题描述

我正在使用带有复制省略的琐碎类型进行一些测试。作为我之前的问题:复制省略和可简单复制的类型

以下代码适用于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; }
};

标签: c++c++17language-lawyerc++20copy-elision

解决方案


推荐阅读