I am doing some tests with trivial types with copy elision. As my prior question : Copy elision and trivially copyable types
The following code works well for std::string
but does not for const char*
. Valgrind returns me "use of uninitialized value of size 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;
}
}
Since copy elision should happen in both cases, I don't understand why it does not work with both cases...
However, using this definition for object make things working (because I think, object becomes not trivially copyable)
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; }
};