Hello, all!
I just started learnin' myself C++ this week and coming from Python, there are a lot of concepts that are similar, but certainly a lot that are different! One thing I like in Python is the concept of properties where accessor and mutator functions are implicitly called whenever a property is gotten or set, respectively. Looking at operator overloading and the conversion operators, I though I could implement this behavior correctly as a good way to teach myself the syntax and inner workings of the language.
I finally figured out (or I think that I figured out) the syntax so that I no longer get compile-time errors with g++ without an "-std" switch, but I am getting segmentation faults now. I have two source files:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
|
// property.hxx:
#ifndef _PROPERTY_H_
#define _PROPERTY_H_
#include <string>
namespace skilly
{
using std::string;
template <typename T>
class property
{
public:
property(T value)
{
set(value);
}
T operator =(T value)
{
set (value);
}
operator T() const
{
return get();
}
T get() const
{
return m_value;
}
T set(T value)
{
m_value = value;
}
protected:
T m_value;
};
}
#endif
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
//testprop.cxx:
#include <iostream>
#ifndef _PROPERTY_H_
#include "property.hxx"
#endif
namespace skilly
{
// strings:
template <>
string property <string>::get() const
{
std::cout << "get string" << std::endl;
return m_value;
}
template <>
string property <string>::set(string value)
{
std::cout << "set string" << std::endl;
m_value = value;
}
}
using namespace std;
using namespace skilly;
int main(int argc, char *argv[])
{
string s = string("Hello, World!");
skilly::property <string> s2 = skilly::property <string> (s);
std::cout << (string)s2 << std::endl;
return 0;
}
|
When I compile with:
g++ -O0 -ggdb -o ./test ./testprop.cxx
I get no error messages, but then when I run, I'm getting a "Segmentation fault (core dumped)" message. I'll follow up with the output I get from valgrind, but it looks to me like it has something to do with temporary values; when I don't use s and try to pass the string("Hello, World!") to the property constructor, I get different errors.
Is there anything here that jumps out at anyone? If there's any more information that is needed, please let me know!