Consider the following example class:
class Foo {
public:
void* const arr_;
Foo() = delete;
Foo(const size_t size, bool high_precision) :
arr_(Initialize(size, high_precision)) {};
template <typename T>
T* GetDataPointer() {
return (T* const)arr_;
}
private:
static void* Initialize(const size_t size, bool high_prec) {
if (high_prec) {
return new double[size];
}
else {
return new float[size];
}
}
};
When I created a shared pointer to a Foo object using std::make_shared
, I often find the array data I initialize displays undefined behavior/becomes corrupted. For example:
std::shared_ptr<Foo> sp_foo = std::make_shared<Foo>(Foo(3,false));
auto foo_data = sp_foo->GetDataPointer<float>();
foo_data[0] = 1.1;
foo_data[1] = 2.2;
foo_data[2] = 3.3;
std::cout << "First Value: " <<
sp_foo->GetDataPointer<float>()[0]; // Sometimes this is 1.1, sometimes it is meaningless.
However, when I initialize the shared pointer using new
, this problem seems to go away.
std::shared_ptr<Foo> sp_foo (new Foo(3,false));
auto foo_data = sp_foo->GetDataPointer<float>();
foo_data[0] = 1.1;
foo_data[1] = 2.2;
foo_data[2] = 3.3;
std::cout << "First Value: " <<
sp_foo->GetDataPointer<float>()[0]; // Correctly prints 1.1
Any thoughts as to what is happening? Small side note: I am constrained to not template the Foo
class and to indeed have a void* const
to the onboard data array.