I'm newbee about c++ and I'm having trouble with destructors. When i create an object and push to a vector that holds class, i can see variable "_path" is initialized. But after i try to reach the variable, i see object calls decontsuctor and i cant see the variable.
Here is the code:
#include <iostream>
#include <vector>
#include <string>
#include "ClassA.h"
A returnA(const char* char_a)
{
return A(char_a);
}
int main() {
std::vector<A> vectorA;
for (int i = 0; i < 10; i++)
{
std::string s = std::to_string(i);
vectorA.emplace_back(returnA(s.c_str()));
}
std::cout << "-------" << std::endl;
for (int i = 0; i < vectorA.size(); i++)
{
vectorA[i].getPath();
}
return 0;
}
class A
{
public:
const char* _path;
A(const char* path);
~A();
void getPath();
};
A::A(const char* path)
{
_path = path;
std::cout << "Obj is constructed! " << _path << std::endl;
}
A::~A()
{
std::cout << "Obj is deconstructed! ";
std::cout << _path << std::endl;
}
inline void A::getPath()
{
std::cout << _path << std::endl;
}
How can i prevent objects not deconstruct themselves and reach their variables without dynamic allocation?