c++ - 复制琐碎类型的省略号,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++ 中的方法覆盖概念
- javascript - 为什么我的粒子在 JavaScript 中永远不会回到中间
- python - 如何传递查询字符串以在模板中呈现视图上下文?
- python-3.x - 如何使用 pyautogui 投射随机密钥?
- reactjs - 在 React Router 中进行两次路由加载或挂载
- etl - 未连接的查找 sql 覆盖问题
- entity-framework - 如何在启动类中注册 dbcontext 以供参考?
- node.js - NodeJS - 如果移动多个文件失败,删除失败的文件
- python-3.x - 添加属性 QtCore.Qt.FramelessWindowHint 后如何从边缘调整窗口大小
- python-3.x - 在 Django DetailView 中添加评论功能?