Are only types with trivial destructor suited for storage for placement new? - destructor

The examples for placement new often use unsigned char arrays as the underlying storage. The steps can be:
create the unsigned char array with new
create an object in this storage with placement new
use object
destroy object
call delte for the unsigned char array to free the array
Point 5. seems only to work if we use a type for the underlying storage with a trivial destructor. Otherwise, we would call the destructor of the underlying storage type but with no object existing there. Technically, we are destructing a bunch of unsigned chars which are not present and we are lucky that the desturctor of the unsigned char type is trivial and so no-op.
What about the following code:
struct A{ /* some members... */ };
struct B{ /* some members... B shall be same size as A */ };
int main()
{
auto ptr_to_a = new A; // A object lives # ptr_to_a
ptr_to_a->~A(); // A object destroyed. no object living # ptr_to_a, but storage is preserved
new (ptr_to_a) B; // B object living # ptr_to_a.
std::launder(reinterpret_cast<b*>(ptr_to_a))->/*...*/; // use B. for this purpose we need std::launder in C++17 or we would store the pointer returned by the placement new and use it without std::launder
std::launder(reinterpret_cast<b*>(ptr_to_a))->~B(); // B object destroyed. no object living # ptr_to_a, but storage is preserved
// at this point there is no object living # ptr_to_a, but we need to hand back the occupied storage.
// a)
delete ptr_to_a; // undefined behavior because no object is sitting # ptr_to_a
// b)
new (ptr_to_a) A; // create an object again to make behavior defined. but this seems odd.
delete ptr_to_a;
// c)
// some method to just free the memory somehow without invoking destructors?
return 0;
}
On https://en.cppreference.com/w/cpp/language/lifetime is written:
As a special case, objects can be created in arrays of unsigned char or std::byte (in which case it is said that the array provides storage for the object) if... .
Does this imply, that its only allowed to use placement new on unsigned char and byte arrays and because they have a trivial destructor my code sample is obsolete?
Otherwise, how about my codesample? Is option b) the only valid solution?
Edit: second examlpe:
struct A{ /* some members... */ };
struct alignas(alignof(A)) B{ /* some members... */ };
int main()
{
static_assert(sizeof(A) == sizeof(B));
A a;
a.~A();
auto b_ptr = new (&a) B;
b_ptr->~B();
return 0;
// undefined behavior because a's destructor gets called but no A object is "alive" (assuming non trivial destructor)
// to make it work, we need to placement new a new A into a?
}

Generally, you wouldn't use the storage returned by an allocation of an unrelated class A to put your B in. You don't even have to have an allocation at all
int main ()
{
char storage[sizeof(B)];
std::aligned_storage<sizeof(B), alignof(B)>::type aligned_storage;
auto b_ptr1 = new (&storage) B; // potentially unaligned
auto b_ptr2 = new (&aligned_storage) B; // guaranteed safe
// use b_ptr1, b_ptr2
b_ptr1->~B();
b_ptr2->~B();
// storage ceases to exist when main returns
}
If you do need to dynamically allocate, I would suggest wrapping the storage in a holder struct, so that you don't end the lifetime of the thing you newed.
struct B_holder
{
std::aligned_storage<sizeof(B), alignof(B)>::type storage;
B * make_B() { return new(&storage) B; }
}
int main()
{
auto holder = std::make_unique<B_holder>();
auto * B_ptr = B_holder->make_B();
// use B_ptr
B_ptr->~B();
// holder ceases to exist when main returns
}

For the most part yes.
You can however do something like this.
struct placed {
char stuff[100];
};
struct stupid {
std::aligned_storage_t<sizeof(placed), alignof(placed)> data;
~stupid() {
std::cout << "stupid gone\n";
}
};
int main() {
auto* pstupid = new stupid;
auto* pplaced = ::new( (void*)&pstupid->data ) placed;
pplaced->~placed();
auto* pstupid2 = ::new( (void*)pstupid ) stupid;
delete pstupid2;
}
but that is, as implied by the type name, pretty stupid. And exceedingly hard to make exception safe without a lot of noexcept guarantees I didn't include above.
I am also not completely certain if delete pstupid2 is legal, as it was created via placement new and not via a simple new expression.

Related

output from move constructor class

class test
{
char *str;
public:
test(char *p_str) /**default constructor**/
{
cout<<"Default\n";
int l = strlen(p_str) + 1;
str = (l ? new char[l] : 0);
memcpy(str,p_str,l);
}
test(const test& ob) /**copy**/
{
cout<<"Copy\n";
int l = strlen(ob.str) + 1;
str = (l ? new char[l] : 0);
memcpy(str,ob.str,l);
}
test(test&& ob) /**move constructor **/
{
cout<<"Move Constructor\n";
str = ob.str;
ob.str = nullptr;
}
void my_swap(test &ob1 , test &ob2) /**swap function**/
{
swap(ob1.str , ob2.str);
}
test& operator=(test ob) /**copy is called because of pass by value **/
{
cout<<"Copy Assignment operator\n";
my_swap(*this,ob);
return *this;
/**copy is destroyed as object passed by value is destroyed just after the function returns;**/
}
~test()
{
cout<<"Destructor\n";
delete[] str;
}
void print_str()
{
cout<<str<<"\n";
}
};
The above class contains simple implementation of rule of 5 in c++.Now when a vector of this class is created as following.
int main()
{
vector<test> vec1;
vec1.push_back(test("Hi!There"));
return 0;
}
I get the following output
Default
Move Constructor
Destructor
Destructor
And when one more object is pushed into the vector like this
int main()
{
vector<test> vec1;
vec1.push_back(test("Hi!There"));
vec1.push_back(test("Hello! There"));
return 0;
}
The output is
Default
Move Constructor
Destructor
Default
Move Constructor
Copy
Destructor
Destructor
Destructor
Destructor
Now my question is why is the copy constructor called in the second case and not the first.
Thanku
Since you have 5 destructor calls instead of 4 I assume that the vector had to reallocate it's internal storage when you tried to push the second item. This means that the vector had to move the first pushed item to the newly allocated (larger) memory area. However when a vector reallocates it storage and has to transfer items from the old memory block the the new one, it may happen that the item is transferred with copy instead of move. Reason: How to enforce move semantics when a vector grows?
In your case the correct solution would be using vec1.reserve(2) (before pushing items) to avoid the unnecessary reallocation even if the reallocation happens with move. Frequent reallocation is often the target of memory usage optimization.

Shall I build a destructor in this classes?

I am currently working on building an ABM model using C++.
I have classes that have the need to interact with each other, because e.g. class B needs to examine values in class A and return some evaluation on it, which then class C might want to read. Classes need not to change other classes values, only to read from them.
Class B in my current implementation has a po
inter to a vector containing all members of Class A. The pointer is there for two order of reason: it makes easier to initialize the vector, and the vector is left in the scope of main so that I can access and loop over it, calling the members of class A for each agent.
My MCVE:
#include <iostream>
#include <vector>
using namespace std;
class A; // Forward declaration
class B{
int id,
some_value;
vector<A> * A_vec;
public:
// Overloaded constructor
B(int ID, vector<A> & PTR)
{
A_vec = & PTR;
id = ID;
some_value = 0;
};
// Copy Constructor
B( const B& that ):
id(that.id),
some_value(that.some_value)
{
// Pointer ??
};
// Non-default destructor -> uncomment leads to seg_fault
/*
~B(){ delete [] A_vec;};
*/
// Assignment operator
B& operator=(const B& that)
{
id = that.id;
some_value = that.some_value;
// Pointer ??
return *this;
};
//Methods to update different variables go here ..
void do_stuff();
};
class A{
B & class2_ref;
vector<double> o;
public:
int stuff;
// Overloaded constructor
A(int STUFF, B & REF, vector<double> O):
class2_ref(REF),
o(O)
{
stuff = STUFF;
};
// Methods to update different variables go here ..
};
void B::do_stuff()
{
int L = A_vec->size();
for(int l = 0; l<L; l++) some_value += (*A_vec)[l].stuff; // Perform some operation
};
int main(){
int I = 5; // Number of objects of A
vector<double> O(12,2); // Some numbers in here
B b(0,A_vec);
for(int i = 0; i< I; i++)
{
A a(i,b,O);
A_vec.push_back(a);
}
b.do_stuff();
cout<< "Debugging MCVE" << endl;
return 0;
}
My question then is:
Should I implement the destructor/copy constructor/assignment operator in class B? What about class A ? If so, can you please point me to the correct syntax(for the destructor the one above in comments leads to seg fault).
My understanding is that this might be one of the case in which I am happy with a "shallow" destruction of the pointer, because both class B and vector<A> will go out of scope at the return statement. class B owns the pointer, which gets destructed when it is due, and the same for vector.
But then, what about the other member from the rule of three?
There is only one object of class B planned, but I might (small chance) want to generalize later on.
if a class have a pointer type, you should implement a destructor, and i would suggest implementing a copy and an assignment operator as well, else you will be dealing with the same object from 2 different places, which could cause you some errors, for example -
void someFunction(B &b)
{
B a = b;
}
B b(0,A_vec);
someFunction(b); //After finishing someFunction, it will try to delete the vector from a , but it is the same vector you used in b.
b.do_stuff(); // Would cause a seg error
And for the destructor syntax, just delete the vector, not its content, it will use the vector default destrctor on the content:
delete A_vec
just make sure you dont use it if its not initialized, i would suggest just building a empty vector on each ctor of the class, that way you wont get a seg fault and you can use delete.

How to dynamically add a key:value property to c++ class, then make it accessible as class.property

In Python I have a flag class that I have found very useful. I'm newbe to c++, and can not seem to replicate this python functionality in c++. Rather than put up c++ code that didn't work, here's what I am looking to replicate, and I need some suggestions on where to go, templates, virtual, or ??
The requirement is being able to dynamically alter the members of the class, in python it's modifying the dict element of the class it's self that enables this.
In python:
import sys
args = []
... loads up args[] with keys:values looping through sys.argv[] ... blah blah blah
class Flag:
def __ init __(self, **args):
self. __ dict __.update(args)
now we enable flag.dynamicproperty
flag = Flag(**dict(args))
An example of use:
$ python script.py somedesc1 someval1 somedesc2 someval2
What this does is enables me to pass in parameters, as above, from the command-line and assign any number of them on-the-fly, and make then accessible by a flag.property (eg flag.somedesc1) call which returns somval1. Another way to maybe think about this is dynamically adding a key:value property to a C++ class.
An example of use in python code :
if flag.somedesc1 != '10': print someval1
I can't seem to make a comparable c++ work. I've looked into polymorphism, but these have to be assigned dynamically and then be accessible as a property of the class.
Ideas??? Surely c++ can do this, I'm just not sure where to start.
Okay, here is the solution I worked out; haven't tested it yet, but should work close enough to fit my needs using this format
flag.find(filename)
enum { filename, workers, runtime };
class flag {
vector<string> helplist;
public:
int add(int argc, char *argv[], string flag, string value, string description) {
string flagvalue;
flagvalue = value;
helplist.push_back(description);
for (int i; i < argv.length(); i++) {
if (argv[i]==flag) {
flagvalue = argv[i+1];
}
}
}
void showhelp() {
for (int i; i < helplist.length(); i++) {
cout << helplist[i] << endl;
}
}
};
No, you can't do this in C++. In C++, the members of a class are defined 100% at compile time. You cannot add any at runtime. The way to do this in C++ would be to have a member variable that's a map<string,string> that holds the key/value pairs, and then have a function string getVariable(string) that returns the value in the dictionary for that key.

struct vs class for writing D wrappers around foreign languages

(note: this is related to Usage preference between a struct and a class in D language but for a more specific use case)
When writing a D interface to, say, C++ code, SWIG and others do something like this:
class A{
private _A*ptr;//defined as extern(C) elsewhere
this(){ptr=_A_new();}//ditto
this(string s){ptr=_A_new(s);} //ditto
~this(){_A_delete(ptr);} //ditto
void fun(){_A_fun(ptr);}
}
Let's assume no inheritance is needed.
My question is: wouldn't it be preferable to use a struct instead of a class for this?
The pros being:
1) efficiency (stack allocation)
2) ease-of-use (no need to write new everywhere, eg: auto a=A(B(1),C(2)) vs auto a=new A(new B(1),new C(2)) )?
The cons being:
require additional field is_own to handle aliasing via postblit.
What would be the best way to do so?
Is there anything else to worry about?
Here's an attempt:
struct A{
private _A*ptr;
bool is_own;//required for postblit
static A opCall(){//cannot write this() for struct
A a;
a.ptr=_A_new();
a.is_own=true;
return a;
}
this(string s){ptr=_A_new(s); is_own=true;}
~this(){if(is_own) _A_delete(ptr);}
void fun(){_A_fun(ptr);}
this(this){//postblit;
//shallow copy: I don't want to call the C++ copy constructor (expensive or unknown semantics)
is_own=false; //to avoid _A_delete(ptr)
}
}
Note the postblit is necessary for cases when calling functions such as:
myfun(A a){}
I suggest that you read this page. The only functions on C++ classes that you can call in D are virtual functions. That means that
D can­not call C++ spe­cial mem­ber func­tions, and vice versa. These in­clude con­struc­tors, de­struc­tors, con­ver­sion op­er­a­tors, op­er­a­tor over­load­ing, and al­lo­ca­tors.
And when you declare a C++ class in D, you use an extern(C++) interface. So, your class/struct would look like this
extern(C++) interface A
{
void fun();
}
However, you'd need another extern(C++) function to allocate any objects of type A, since it's C++ code that has to do that as the D code doesn't have access to any of the constructors. You'd also need a way to pass it back to C++ code to be deleted when you're done with it.
Now, if you want to wrap that interface in a type which is going to call the extern(C++) function to construct it and the extern(C++) function to delete it (so that you don't have to worry about doing that manually), then whether you use a class or struct depends entirely on what you're trying to do with it.
A class would be a reference type, which mirrors what the C++ class actually is. So, passing it around would work without you having to do anything special. But if you wanted a guarantee that the wrapped C++ object was freed, you'd have to do so manually, because there's no guarantee that the D class' finalizer would ever be run (and presumably, that's where you'd put the code for calling the C++ function to delete the C++ object). You'd have to either use clear (which will actually be renamed to destroy in the next release of the compiler - dmd 2.060) to destroy the D object (i.e. call its finalizer and handle the destruction of any of its member variables which are value types), or you'd have to call a function on the D object which called the C++ function to delete the C++ object. e.g.
extern(C++) interface A
{
void fun();
}
extern(C++) A createA();
extern(C++) void deleteA(A a);
class Wrapper
{
public:
this()
{
_a = createA();
}
~this()
{
deleteA(_a);
}
auto opDispatch(string name, Args...)(Args args)
{
return mixin("_a." ~ name ~ "(args)");
}
private:
A _a;
}
void main()
{
auto wrapped = new Wrapper();
//do stuff...
//current
clear(wrapped);
//starting with dmd 2.060
//destroy(wrapped);
}
But that does have the downside that if you don't call clear/destroy, and the garbage collector never collects your wrapper object, deleteA will never be called on the C++ object. That may or may not matter. It depends on whether the C++ object really needs its destructor to be called before the program terminates or whether it can just let its memory return to the OS (without its destructor being called) when the program terminates if the GC never needs to collect the wrapper object.
If you want deterministic destruction, then you need a struct. That means that you'll need to worry about making the struct into a reference type. Otherwise, if it gets copied, when one of them is destroyed, the C++ object will be deleted, and the other struct will point to garbage (which it will then try and delete when it gets destroyed). To solve that, you could use std.typecons.RefCounted. Then you get something like
extern(C++) interface A
{
void fun();
}
extern(C++) A createA();
extern(C++) void deleteA(A a);
struct Wrapper
{
public:
static Wrapper opCall()
{
Wrapper retval;
retval._a = createA();
return retval;
}
~this()
{
if(_a !is null)
{
deleteA(_a);
_a = null;
}
}
auto opDispatch(string name, Args...)(Args args)
{
return mixin("_a." ~ name ~ "(args)");
}
private:
A _a;
}
void main()
{
auto wrapped = RefCounted!Wrapper();
//do stuff...
}
You could also define the wrapper so that it has the ref-counting logic in it and avoid RefCounted, but that would definitely be more complicated.
Regardless, I would definitely advise against your suggestion of using a bool to mark whether the wrapper owns the C++ object or not, because if the original wrapper object gets destroyed before all of the copies do, then your copies will point to garbage.
Another option if you did want the C++ object's copy constructor to be used (and therefore treat the C++ object as a value type) would be to add an extern(C++) function which took the C++ object and returned a copy of it and then use it in a postblit.
extern(C++) A copyA(A a);
this(this)
{
if(_a !is null)
_a = copyA(a);
}
Hopefully that makes things clear enough.

Timer Thread with passed Function* and Param

I'm working on finishing up my server for my first iPhone application, and I want to implement a simple little feature.
I would like to run a function (perhaps method as well), if another function returns a certain value after a certain waiting period. Fairly simple concept.... right?
Here's my basic foundation.
template <typename T,class TYP>
struct funcpar{
T (*function)(TYP);
TYP parameter;
funcpar(T (*func)(TYP),TYP param);
funcpar& operator=(const funcpar& fp);
};
The goal here is to be able to call funcpar::function(funcpar::parameter) to run the stored function and parameter, and not have to worry about anything else...
When I attempted to use a void* parameter instead of the template, I couldn't copy the memory as an object (because I didn't know what the end object was going to be, or the beginning for that matter) and when I tried multiple timers, every single object's parameter would change to the new parameter passed to the new timer... With the previous struct I have a
question:
Is it possible to make an all-inclusive pointer to this type of object inside a method of a class? Can I templatize a method, and not the whole class? Would it work exactly like a function template?
I have a managing class that holds a vector of these "jobs" and takes care of everything fairly well. I just don't know how to use a templatized function with the struct, or how to utilize templates on a single method in a class..
I'm also utilizing this in my custom simple threadpool, and that's working fairly well, and has the same problems...
I have another question:
Can I possibly store a function with a parameter before it's run? Something like toRun = dontrunmeyet(withThisParameter);? Is my struct even necessary?
Am I going about this whole thing incorrectly?
If this is overly ambiguous, I can set you up with my whole code for context
In order to create a class method that takes a template parameter, yes, it would work almost exactly like a function template. For example:
class A
{
public:
template<typename T>
void my_function(const T& value) { }
};
int main()
{
A test;
test.my_function(5);
return 0;
}
Secondly, for your structure, you can actually turn that into a functor-object that by overloading operator(), lets you call the structure as-if it were a function rather than having to actually call the specific function pointer members inside the structure. For instance, your structure could be re-written to look like this:
#include <iostream>
template <class ReturnType, class ParameterType>
class funcpar
{
private:
ReturnType (*function)(ParameterType);
ParameterType parameter;
public:
funcpar(ReturnType (*func)(ParameterType),ParameterType param):
function(func), parameter(param) {}
funcpar& operator=(const funcpar& fp);
//operator() overloaded to be a function that takes no arguments
//and returns type ReturnType
ReturnType operator() ()
{
return function(parameter);
}
};
int sample_func(int value)
{
return value + 1;
}
int main()
{
funcpar<int, int> test_functor(sample_func, 5);
//you can call any instance of funcpar just like a normal function
std::cout << test_functor() << std::endl;
return 0;
}
BTW, you do need the functor object (or your structure, etc.) in order to bind a dynamic parameter to a function before the function is called in C/C++ ... you can't "store" a parameter with an actual function. Binding a parameter to a function is actually called a closure, and in C/C++, creating a closure requires a structure/class or some type of associated data-structure you can use to bind a function with a specific parameter stored in memory that is used only for a specific instance of that function call.