I am following an online tutorial which is quite similar to my code, but not exactly the same. I have modified it so that I can have a better understanding of it, but I am having problems getting/returning the string value from the inline function. The string value becomes empty as soon as the compiler exits the last curly bracket of Another.cpp.
Is there any way to solve my issue without changing the structure of my files as well as the code? Particularly, I don't want to change anything from the Another.h. Please, if someone can explain what could be the reason behind the inline function here as well, will really appreciate that.
Another.h
#pragma once
#include<iostream>
#include"Temple.h"
#include<memory>
namespace NamespaceAn
{
class Test
{
public:
static void Init();
inline static std::shared_ptr<Outside::Inside>& GetString() { return s_String; }
private:
static std::shared_ptr<Outside::Inside> s_String;
};
}
Another.cpp
#include "Another.h"
#include<string>
namespace NamespaceAn
{
std::shared_ptr<Outside::Inside>Test::s_String;
void Test::Init()
{
//This s_String value is getting disapprear as soon as the compiler get out of the curly bracket
auto s_String = Outside::Inside("asdf");
//below all are commented out for the Another.cpp
//std::string Ast = "asdf";
/*std::string Ast = "asdf";
auto s_String = new Outside::Inside(Ast);*/
/*Outside::Inside* ob = new Outside::Inside(Ast);
auto s_String = &(ob->Get());*/
// ***** Attention ****
//no operator "=" matches the operands and binary '=' no operator found which takes a right-hand ooperand of type std::string*(no acceptable conversion)
//s_String = &(ob->Get());
//auto s_String = Ast;
//auto s_String = Outside::Inside("asdf");
//auto s_String = new Outside::Inside("asdf");
//s_String = reinterpret_cast<Ast>;
//*s_String = &(Outside::Inside("asdf"));
//s_String = reinterpret_cast<Outside::Inside*>(&Outside::Inside("asdf"));
}
}
Temple.h
#pragma once
#include <string>
namespace Outside
{
class Inside
{
std::string m_String = "tesi";
public:
Inside(std::string x)
{
m_String = x;
}
std::string Get()
{
return m_String;
}
/*std::string* m_String;
public:
Inside(std::string &x)
{
m_String = &x;
}
std::string Get()
{
return
*m_String;
}*/
/*template<typename T>
static T Set(T x)
{
return T;
}*/
};
}
main.cpp
#pragma once
#include<iostream>
#include"Another.h"
#include<memory>
int main()
{
NamespaceAn::Test::Init();
/*auto asdf = NamespaceAn::Test::GetString();
std::cout << asdf << std::endl;*/
std::cout << NamespaceAn::Test::GetString();
std::cin.get();
}
Extra
Inside of Another.cpp, I have also tried the following code:
std::string Ast = "asdf";
Outside::Inside* ob = new Outside::Inside(Ast);
auto s_String = &(ob->Get());
#pragma oncein yourmain.cppis very odd.inline static std::shared_ptr<Outside::Inside>& GetString(...is odd, in my opinion. Should either returnstd::shared_ptr<Outside::Inside>orOutside::Inside const&orOutside::Insideorstd::string.