C++ wrap C struct *and* and functions - c++

I'm trying to wrap a C library which uses patterns like this:
Thing* x= new_thing_("blah");
Thing* tmp= thing_copy(x);
free_thing(tmp);
Other* y=get_other(x,7);
char* message=get_message(x,y);
free_thing(x);
free_other(y);
In c++, I'd like to be able to do something like
auto_ptr<CXXThing> x=new CXXThing("blah");
auto_ptr<CXXThing> tmp=new CXXThing(*x);
auto_ptr<CXXOther> y=x->get_other(7);
char* message = y->get_message();
Obviously, CXXOther wraps a pointer to a CXXThing as well. So the problem I'm encountering is that essentially I'd like to just "insert" functions and members into existing structs (I think this is known as the "Mixin" idea).
The problem is that if I include a Thing as an element of the CXXThing, then I don't know how I'd declare the constructor, and if I include a pointer to the wrapped class, then I have an extra level of useless indirection.
How should I wrap it so that this is possible? (An answer of "What you want to do is not best/possible... here is the proper way" is also acceptable.)

Instead of using auto_ptrs, you can use the RAII idiom more directly. Here's one way you can do it:
A CXXThing class that wraps a Thing:
class CXXThing
{
public:
// Acquire a Thing
explicit CXXThing(const char* str) : x(::new_thing_(str)) {}
// Copy a Thing
CXXThing(const CXXThing& rhs) : x(::thing_copy(rhs.x)) {}
// Copy-and-swap idiom
CXXThing& operator=(CXXThing rhs)
{
swap(*this, rhs);
return *this;
}
// Release a Thing
~CXXThing() { ::free_thing(x); }
friend void swap(CXXThing& lhs, CXXThing& rhs)
{
Thing* tmp = lhs.x;
lhs.x = rhs.x;
rhs.x = tmp;
}
private:
Thing* x;
friend class CXXOther;
};
A CXXOther class that wraps an Other:
class CXXOther
{
public:
// Acquire an Other
explicit CXXOther(CXXThing& thing, int i) : y(::get_other(thing.x, i)) {}
// Release an Other
~CXXOther() { ::free_other(y); }
// Get a message
char* get_message(const CXXThing& x) { return ::get_message(x.x, y); }
private:
// Instaces of Other are not copyable.
CXXOther(const CXXOther& rhs);
CXXOther& operator=(const CXXOther& rhs);
Other* y;
};
Translating your C code into C++ code with the above classes:
int main()
{
CXXThing x("blah");
{
CXXThing tmp = x;
} // tmp will go away here.
CXXOther y(x, 7);
char* msg = y.get_message(x);
return 0;
}

Related

Proper API for access data members of container<T>

I have the following class:
class Document
{
public:
Document():
// default values for members,
// ...
m_dirty{false}{}
// Accessor functions
template<class OutputStream>
Document& save(OutputStream stream)
{
// Write stuff to `stream`
// ...
m_dirty = false;
return *this;
}
bool dirty() const { return m_dirty; }
private:
Size2d m_canvas_size;
LayerStack m_layers;
LayerIndex m_current_layer;
std::vector<Palette> m_palettes;
PaletteIndex m_current_palette;
ColorIndex m_current_color;
std::vector<std::string> m_palette_names;
std::vector<std::string> m_layer_names;
bool m_dirty;
};
Should the class have public member functions for modifying an element of say m_palettes directly, like
Document& color(PaletteIndex, ColorIndex, Color)
, or is it more "correct", to only allow access to the entire vector, through a pair of API:s
std::vector<Palette> const& palettes();
Document& palettes(std::vector<Palette>&&);
The first option would be more efficient, since it would not require to create a temporary copy of the data member, but consistent use of this design would make the interface bloated. It would require "deep" getters and setters for every container in the class.
Notice the dirty flag. Thus, the following would break the abstraction:
std::vector<Palette>& palettes();
You might have Proxy to "propagate" dirty flag from Palette modification, something like:
template <typename T>
class DirtyProxy
{
T& data;
bool& dirty;
public:
DirtyProxy(T& data, bool& dirty) : data(data), dirty(dirty) {}
~DirtyProxy() { dirty = true;}
DirtyProxy(const DirtyProxy&) = delete;
T* operator ->() { return data; }
};
And then
DirtyProxy<Palette> palette(std::size_t i) { return {m_palettes.at(i), dirty}; }
I think the most robust way to solve it is to use a a callback. An issue with the proxy is that it would not handle the case where the the client code throws an exception (assuming strong exception guarantee). Testcase:
try
{
auto property_proxy = obj.getProperty();
// an exception is thrown here...
property_proxy->val = x; // Never updated
}
catch(...)
{}
assert(!obj.dirty());
will fail, because the dtor always sets the dirty flag. However with a callback
class Foo
{
public:
template<class F>
Foo& modifyInSitu(F&& f)
{
f(x);
m_dirty = true;
return *this
}
};
will only update m_dirty, when f(x) does not throw.

Is overloading operator() for a reconstruction a good practice?

I was thinking of the following scenario:
class A {
private:
std::string id;
std::array<std::string, 128> data;
public:
A(const std::string& id) : id(id) {}
A(const A& other) : id(other.id), data(other.data) {}
virtual ~A(){}
//to override the intern data
A& operator=(const A& other) {
this->data = other.data;
return *this;
}
//to override the whole element
A& operator()(const A& other) {
this->id = other.id;
this->data = other.data;
return *this;
}
};
As you can see, my idea was to use operator= to override the internal data and operator() to override the whole element. I was inspired by the constructor which would allow A a(anOtherA); to construct the element and I would like to override this for a re-construction. Now I don't now if this would be smart overloading this because it's actually the function call operator.
Is overloading operator() for a reconstruction a good practice?
In short no, that isn't good practice. Such just obfuscates what is done under the hood.
Providing a setter for data and use the code you provided in your overloaded operator() for the implementation of the assignment operator=() would provide the clearer and naturally expected semantics:
class A {
private:
std::string id;
std::array<std::string, 128> data;
public:
A(const std::string& id) : id(id) {}
A(const A& other) : id(other.id), data(other.data) {}
~A(){}
//to override the intern data
A& operator=(const A& other) {
id = other.id;
data = other.data;
return *this;
}
//to override the intern data
void setData(const A& other) {
data = other.data;
}
void setData(const std::array<std::string, 128>& data_) {
data = data_;
}
};
The semantics of the operator() isn't that clearly defined (vs the operator=()) beyond you can make a call of your class looking like a "normal" function call (which is mostly useful with templates taking your type as a parameter).
But I'd expect it more to do some action instead of changing the internal state of the class.
Regarding the style, instead of the set / get prefixes for getter/setter functions I prefer what's done in the c++ standard library, (like e.g. with the std::ios_base::flags() property):
class A {
private:
// ...
std::array<std::string, 128> data_;
public:
const std::array<std::string, 128>& data() const {
return data_;
}
void data(const std::array<std::string, 128>& data) {
data_ = data;
}
// ...
};
great answer from πάντα ῥεῖ so please upvote that answer, not this one.
As you write, and more importantly, read more c++ you will come to appreciate people who name methods and functions with natural, meaningful names.
For most of us, if we see code like this:
X x;
Y y;
x(y);
We would think, before even looking at the declarations of X and Y, that X is some kind of function object (i.e. it does something) and Y is some kind of data or state object - it likes having things done to it, or it supplies data or services.
As a side note, a Haskell programmer would naturally assume that Y is also a function, but that's another story.
If your implementation of X::operator()(Y) does not "do X-type stuff with or to a Y" then it is probably inappropriately named.
If Y actually represents new state for X, and X intends to 'reset' itself using the data in Y, then the method should probably be called... reset:
X x;
Y y;
x.reset(y); //ok, this is telling a better story
With reasonable names we can tell a narrative with our code:
void processResults(XFactory& factory, std::istream& is) {
while(is) {
auto x = X::createFrom(factory);
x.collectNResults(is, 10);
auto a = x.takeAverage();
storeAverage(a);
x.reset(y);
}
}
Now even without looking up the definitions of the various classes I can get a sense of the general narrative. It's easier on the eye and I'm going to be able to hone in on the bits I need to see much more quickly than:
void processResults(XFactory& factory, std::istream& is) {
while(is) {
auto x = X(factory);
x(is, 10);
auto a = x();
x(averageStore);
x(y);
}
}
Which is what I'd have if I wrote every operation on an X in terms of a call operator which, much like corporate tax avoidance, is actually perfectly legal, but nevertheless happens to upset other people because they end up paying the price for your selfishness.

What is the use of C++ Transparent Class Wrapper

What is call "Transparent Class Wrapper" in C++
Why it is call "Transparent..."
What is the use of it (What cannot do without 'Transparent Class Wrapper').
Appreciate some conceptual explanation.
A transparent class wrapper is a wrapper around a type, where the wrapper behaves the same as the underlying type - hence "transparent".
To explain it as well as its use, here's an example where we wrap an int but overload operator++() to output a message whenever it is used (inspired by this thread):
class IntWrapper {
int data;
public:
IntWrapper& operator++() {
std::cout << "++IntWrapper\n";
data++;
return *this;
}
IntWrapper(int i) : data(i) {}
IntWrapper& operator=(const IntWrapper& other)
{
data = other.data;
return *this;
}
bool operator<(const IntWrapper& rhs) const { return data < rhs.data; }
// ... other overloads ...
};
We can then replace usages of int with IntWrapper if we choose to:
for (int i = 0; i < 100; ++i) { /* ... */ }
// becomes
for (IntWrapper i = 0; i < 100; ++i) { /* ... */ }
Except the latter will print a message whenever preincrement is called.
Note that I supplied a non-explicit constructor IntWrapper(int i). This ensures that whenever I use an int where an IntWrapper is expected (such as IntWrapper i = 0), the compiler can silently use the constructor to create an IntWrapper out of the int. The Google C++ style Guide discourages single-argument non-explicit constructors for precisely this reason, as there may be conversions where you didn't expect, which hurts type safety. On the other hand, this is exactly what you want for transparent class wrappers, because you do want the two types to be readily convertible.
That is:
// ...
explicit IntWrapper(int i) ...
// ...
IntWrapper i = 0; // this will now cause a compile error
Most likely, you're referring to a lightweight inline (header file) wrapper class, though I'm not familiar with the term. Adding a level of abstraction like this is useful in permitting generic client code.

Chaining calls to temporaries in C++

I have a class that does a transformation on a string, like so
class transer{
transer * parent;
protected:
virtual string inner(const string & s) = 0;
public:
string trans(const string & s) {
if (parent)
return parent->trans(inner(s));
else
return inner(s);
}
transer(transer * p) : parent(p) {}
template <class T>
T create() { return T(this); }
template <class T, class A1> // no variadic templates for me
T create(A1 && a1) { return T(this, std::forward(a1)); }
};
So I can create a subclass
class add_count : public transer{
int count;
add_count& operator=(const add_count &);
protected:
virtual string inner(const string & s) {
return std::to_string((long long)count++) + s;
}
public:
add_count(transer * p = 0) : transer(p), count(0) {}
};
And then I can use the transformations:
void use_transformation(transer & t){
t.trans("string1");
t.trans("string2");
}
void use_transformation(transer && t){
use_trasnformation(t);
}
use_transformation(add_count().create<add_count>());
Is there a better design for this? I'd like to avoid using dynamic allocation/shared_ptr if I can, but I'm not sure if the temporaries will stay alive throughout the call. I also want to be able to have each transer be able to talk to its parent during destruction, so the temporaries also need to be destroyed in the right order. It's also difficult to create a chained transformation and save it for later, since
sometrans t = add_count().create<trans1>().create<trans2>().create<trans3>();
would save pointers to temporaries that no longer exist. Doing something like
trans1 t1;
trans2 t2(&t1);
trans3 t3(&t2);
would be safe, but annoying. Is there a better way to do these kinds of chained operations?
Temporaries will be destructed at the end of the full expression, in the
reverse order they were constructed. Be careful about the latter,
however, since there are no guarantees with regards to the order of
evaluation. (Except, of course, that of direct dependencies: if you
need one temporary in order to create the next—and if I've
understood correctly, that's your case—then you're safe.)
If you don't want dynamic allocation you either pass the data which is operated on to the function that initiates the chain, or you need a root type which holds it for you ( unless you want excessive copying ). Example ( might not compile ):
struct fooRef;
struct foo
{
fooRef create() { return fooRef( m_Val ); }
foo& operator=( const fooRef& a_Other );
std::string m_Val;
}
struct fooRef
{
fooRef( std::string& a_Val ) : m_Val( a_Val ) {}
fooRef create() { return fooRef( m_Val ); }
std::string& m_Val;
}
foo& foo::operator=( const fooRef& a_Other ) { m_Val = a_Other.m_Val; }
foo startChain()
{
return foo();
}
foo expr = startChain().create().create(); // etc
First the string lies on the temporary foo created from startChain(), all the chained operations operates on that source data. The assignment then at last copies the value over to the named var. You can probably almost guarantee RVO on startChain().

Is there C++ lazy pointer?

I need a shared_ptr like object, but which automatically creates a real object when I try to access its members.
For example, I have:
class Box
{
public:
unsigned int width;
unsigned int height;
Box(): width(50), height(100){}
};
std::vector< lazy<Box> > boxes;
boxes.resize(100);
// at this point boxes contain no any real Box object.
// But when I try to access box number 50, for example,
// it will be created.
std::cout << boxes[49].width;
// now vector contains one real box and 99 lazy boxes.
Is there some implementation, or I should to write my own?
It's very little effort to roll your own.
template<typename T>
class lazy {
public:
lazy() : child(0) {}
~lazy() { delete child; }
T &operator*() {
if (!child) child = new T;
return *child;
}
// might dereference NULL pointer if unset...
// but if this is const, what else can be done?
const T &operator*() const { return *child; }
T *operator->() { return &**this; }
const T *operator->() const { return &**this; }
private:
T *child;
};
// ...
cout << boxes[49]->width;
Using boost::optional, you can have such a thing:
// 100 lazy BigStuffs
std::vector< boost::optional<BigStuff> > v(100);
v[49] = some_big_stuff;
Will construct 100 lazy's and assign one real some_big_stuff to v[49]. boost::optional will use no heap memory, but use placement-new to create objects in a stack-allocated buffer. I would create a wrapper around boost::optional like this:
template<typename T>
struct LazyPtr {
T& operator*() { if(!opt) opt = T(); return *opt; }
T const& operator*() const { return *opt; }
T* operator->() { if(!opt) opt = T(); return &*opt; }
T const* operator->() const { return &*opt; }
private:
boost::optional<T> opt;
};
This now uses boost::optional for doing stuffs. It ought to support in-place construction like this one (example on op*):
T& operator*() { if(!opt) opt = boost::in_place(); return *opt; }
Which would not require any copy-ing. However, the current boost-manual does not include that assignment operator overload. The source does, however. I'm not sure whether this is just a defect in the manual or whether its documentation is intentionally left out. So i would use the safer way using a copy assignment using T().
I've never heard of such a thing, but then again there are lots of things I've never heard of. How would the "lazy pointer" put useful data into the instances of the underlying class?
Are you sure that a sparse matrix isn't what you're really looking for?
So far as I know, there's no existing implementation of this sort of thing. It wouldn't be hard to create one though.