C++ Complete Roadmap 2022



C++ Complete Roadmap 2022

In this blog we are going to discuss complete roadmap for c++ in 2022. I will give you only topics and if you like my post then follow my Blogs. Lets Start:-👇



C++ Complete Roadmap 2022



New & Trending Topics:👇

Top 10 Trending Technologies to Learn in 2022
Top 10 Programming Languages You Must Know In 2022
Machine Learning Complete Roadmap 2022



Complete Roadmap 2022:-👇

Python Complete Roadmap 2022
Machine Learning Complete Roadmap 2022
C++ Complete Roadmap 2022
Java Complete Roadmap 2022
Data Structure Complete Roadmap 2022



Some Laravel Tutorial for developer:👇

Laravel 8 Interview Questions and Answers in 2022 (Part #1)
Laravel 8 Interview Questions and Answers in 2022 (Part #2)
Advance Laravel 8 Interview Questions and Answers 2022
Everything About Laravel 8 Composer 2022 | Composer in Laravel 8
Laravel Jetstream vs Laravel ui vs Breeze



Python Concept and Projects:-👇

10 Best Python Libraries For Machine Learning
Alarm Clock in Python with GUI
Tic Tac Toe Game Using Pygame in Python

Thankyou for reading my blogs.



My Website:👇

CodexAshish


Source link

Why many Unix structs have prefixes

One thing I’ve long been curious about is why some Unix C struct fields are named such that they are prefixed by a common abbreviation. For example, for the sockaddr_in struct:

struct sockaddr_in 
    short           sin_family;
    unsigned short  sin_port;
    struct in_addr  sin_addr;
;

all fields are prefixed by sin, an abbreviation for sockaddr_in. There are several other examples, as well, e.g., struct stat.

I originally thought it was perhaps just a style quirk of the original Unix authors. I tried searching for things like “early C style,” but never found anything.

I’ve also thought that perhaps they named the fields that way to allow the use of short pointer names like p. (We are after all talking about guys who named commands cp, rm, etc.) For example, given:

p->st_mode   // You know 'p' is a stat*.
q->mode      // You have no idea what this is.

The prefix of st_ allows you to know the type of p just by looking at it whereas you’d have to find the declaration of q to know what it means. Non-prefixed fields would require putting a mnemonic in the pointer itself:

pstat->mode  // Clear, but more keystrokes.

Prefixes also make fields easily grepable. Both rationales seem reasonable, right?

However, I finally stumbled across the real answer: early C compilers had only a single, global symbol table, so they added prefixes to struct fields to avoid collisions. 😮 Once C compilers improved, this style largely faded away.†

† Though I’ve since learned that Solaris’ internal style guide still recommends this style to this day, even in new code:

Systematic prefix conventions for … structure or union member names can be useful.

But it doesn’t elaborate as to why, specifically.


Source link

How do I use variable-arguments (varargs) in C++ (effectively)?

So, C++ extends C, and as that being the case, the implementation of varargs persisted (and hasn’t changed, since it could break already existing code).

In C, you could do #include <stdarg.h>, which included some functions for navigating the arguments.
But now most of C’s original .h files are deprecated (in C++).
So I’m wondering, what’s the effective way of using varargs in C++?


Source link

Clean Architecture Solution Template

I’ve become a huge fan of the Clean Architecture pattern when working on .NET API’s. I won’t go into a ton of detail here, as there are a lot of great resources out there on the subject already, including from the person that I first learned it from, Jason Taylor. If you’re unfamiliar with this pattern, do yourself a favor and check out this presentation by Jason from the GOTO 2019 conference:

But at the 10,000 foot level, an API project using the Clean Architecture pattern has 4 separate projects (along with the necessary unit testing projects):

  • Domain – This project is meant to hold the domain entities of the application. The classes in this project map to the data tables or records in whatever data store the application is configured to use.
  • Application – This project contains the business logic and rules that make the application as a whole run as it’s supposed to. It directly references the Domain project, but no other projects within the solution.
  • Infrastructure – This project contains the implementation of any logic that needs to communicate with outside entities, such as a database, the file system, other HTTP API’s, and so forth. It references the Application project to gain access to application contracts that it will then implement for accessing the aforementioned external entities.
  • Api – This is the front-end of the application, and provides the start-up code and the API endpoint entry points.



Solution Template Nuget Package

I’ve created a Nuget package called StaticSphere.CleanArchitecture.Api, and published it to Nuget.org. You can install it using the following command:

dotnet new --install StaticSphere.CleanArchitecture.Api

Once installed, you can create a new solution by running the following command:

dotnet new clean-arch <<parameters>>

When executed, you’ll get a full .NET 6 ASP.NET API solution that contains the following folder structure (assuming you named to the solution HelloWorld):

  • src
    • HelloWorld.Api
    • HelloWorld.Application
    • HelloWorld.Domain
    • HelloWorld.Infrastructure
  • tests
    • HelloWorld.Api.Tests
    • HelloWorld.Application.Tests
    • HelloWorld.Infrastructure.Tests

The projects are all .NET 6 applications with nullable references types and implicit usings enabled. The unit testing projects use Xunit out of the box. There are also support files such as .gitignore, .editorconfig, etc.

There are parameters that can be passed to the dotnet new command that alter the solution that is created:

  • –includeTests – Determines if the test projects should be included or not. Default value: true
  • –skipRestore – If specified, skips the automatic restore of the project on create. Default value: false
  • –useStartup – Determines if the API project should use Startup.cs instead of the newer Minimal API style Program.cs file. Default value: false
  • –includeEF – If set, the created solution will include Entity Framework Core, and will be configured to use the specified provider (only these providers are currently supported)
    • postgres – Adds Postgres Entity Framework configuration
    • sqlserver – Adds SQL Server Entity Framework configuration



Open Source

The Nuget package that contains the solution template is completely free and open source, and is MIT licensed. The Nuget package can be found here, and the source code for the template can be found here. If you have any suggestions, or would like to contribute to the template, please let me know!


Source link

Is there a way to convert dynamically allocated memory to static memory OR copy ptr contents in C/C++?

For reference, static memory is memory that is memory that is assigned, managed, and freed for you (an example is char const* str = "Hello World!";).
C/C++ will clean that string up for you.

Dynamically allocated memory is memory you request, manage, and must clean yourself (an example is Type_t* array = malloc( sizeof(Type_t)*arrLength );).

I’m messing around with C strings in C++, even testing ideas for my own String type. – And I was creating a String +(char c) method, when I thought of something: “How can I return a String object whose str property is statically allocated, and not dynamically allocated?”.
Since the only method of adding a character to an immutable string I can think of involves using malloc( (oldStrLen+1)*sizeof(char) ), which is dynamically allocated.

So, is there a way I can copy the contents of a pointer to a new statically allocated pointer, or convert dynamically allocated memory to statically allocated memory in C/C++?

Thanks!
Cheers!


Source link

When does a pointer become dangling in C/C++? | Why isn't this example dangling?

All testing has been done on SoloLearn‘s C++ playground.

So, I was planning on making a post on a custom pointer datatype, and I was playing around with (raw-)pointers, and I wanted to test something, to see if I could (purposefully) get a pointer to dangle, so I tried something I was certain would work:

int main() 
    int* p;
    
        int i = 10;
        p = &i;
    
    std::cout << p;

and I was baffled when I saw 10 in the output box.
So, I tried (virtually) the same thing in C:

int main() 
    int* p;
    
        int i = 10;
        p = &i;
    
    printf("%d", *p);

and I got 10 again.

I thought the conditions for a pointer to become dangling was for the referenced value to leave the current scope. But as it’s apparent, even though i (and its value) leaves the scope. (Yes, it is leaving the scope, for anyone who wants to object. This is called a guard-scope, and allows temporary variables to exist.)
So, what are the actual conditions for a pointer to become dangling? And/or why is my example NOT dangling?

Thanks!
Cheers!


Source link

Is there a way to have raw-types in (modern) C++?



What are “raw” types?

Raw types(in Java) is a type who has type-arguments (generics/templates*), but whose type-arguments are not specified in a declaration.
Consider the following (Java) code:

class NeverRaw1 
    NeverRaw1(int i)  this.value = i; 
    int value;


class PossiblyRaw<T> 
    PossiblyRaw(T v)  this.value = v; 
    T value;


class NeverRaw2 extends PossiblyRaw<int> 
    NeverRaw2(int i)  this.value = i; 


// ... Some code later...

// This isn't raw because a type argument is specified.
PossiblyRaw<int> notRaw = new PossiblyRaw<>(10);
// This IS raw because none are specified
PossiblyRaw uncooked = new PossiblyRaw<int>(10);

// Invalid. Mismatched types.
notRaw = new PossiblyRaw<float>(10.56);
// Valid. No type mismatch because none is specified.
uncooked = new PossiblyRaw<float>(10.56);



Why would you want types?

So, the first thought that probably popped into your head is “Hey. Isn’t that not type-safe?”, and to that, I say “Yes. It can be unsafe at times. But then it can also be utilized.”.

So? Where can I use this?
Well, here’s where I’m stuck. – I’m implementing a Token type for Janky, and I want to have a parse(std::string|char*) function that returns an array of Token.
How is this a problem?
It’s a problem because even if you want to return an array of something, you must define the template arguments.
My Token type is written as such:

template<typename T, T v> struct Token 
    T              value = v;
    TokenType      type = TokenType::_UNASSIGNED;
    unsigned short col = 0;
    unsigned short ln = 0;
;

And I can’t create any abstraction, since all pieces of this structure are important to have. — And because members aren’t preserved when you say a piece of data is of its parent type.



So…

What’s the best solution here?

Thanks!
Cheers!


Source link

Rust Function Pointers Across FFI Boundary

Hi DEV – it’s been ages! I’m stumped on a problem, and remembered my old adage: “ask DEV stuff, they know things”. So, here’s hoping someone can unstick me!

I’m trying to store a function defined in C in a Rust struct, and call it from the Rust side. The rest of my FFI seems to be hooked up okay, but I’m getting a segfault when I make the actual function call. Debugging sessions have not proved useful.

I’ll try to keep the context streamlined, but let me know if you need more to see what’s going on. The full code is on the FFI branch of this repo.

First, here’s the C externs, the function I’m pointing to, and the passage across the FFI boundary:

typedef struct scheduler scheduler_t;
typedef struct job job_t;
typedef void (*unit_to_unit_t)(void);

extern void run(job_t *, scheduler_t *, unit_to_unit_t);
extern job_t *every(uint32_t);
extern job_t *seconds(job_t *);

// Define a job
void job(void)

    //printf("Hello!  It is now %sn", now());
    printf("Hello!");


run(seconds(every(8)), scheduler, job);

Super exciting stuff. The commented out line calls a now()function that returns a char *, but I wanted to get anything working first. The every() function returns job_t *, and seconds() takes a job_t * and returns a job_t *, which is finally passed into run(). I have a typedef named unit_to_unit_t for the job function pointer – it’s a function taking no arguments and returning nothing. The scheduler is also an FFI entity.

This is the definition of run() on the Rust side:

#[no_mangle]
pub unsafe extern "C" fn run(job: *mut Job, scheduler: *mut Scheduler, work: *const fn() -> ())  eprintln!("Error: ", e));

I’m passing the C function as the last argument here, and trying to cast it to work. This step doesn’t complain, seems to go okay.

On the Rust side, when that job.run() method gets called, the following trait/struct is used to store the function pointer and call it:

pub trait Callable 
    /// Execute this callable
    fn call(&self) -> Option<bool>;
    /// Get the name of this callable
    fn name(&self) -> &str;


/// A named callable function taking no parameters and returning nothing.
#[derive(Debug)]
pub struct UnitToUnit 
    name: String,
    work: fn() -> (),


impl UnitToUnit 
    pub fn new(name: &str, work: fn() -> ()) -> Self 
        Self 
            name: name.into(),
            work,
        
    


impl Callable for UnitToUnit 
    fn call(&self) -> Option<bool> 
        // gets HERE just fine...
        (self.work)();
        None
    
    fn name(&self) -> &str 
        &self.name
    

This all works fine with Rust function pointers. I determined that with the C version, we do get inside the call() implementation – the segfault happens when I use (self.work)();

I’m not sure if it’s relevant, but the actual call is triggered here in C:

extern void run_pending(scheduler_t *);    

// Run some jobs
for (int i = 0; i < 100; i++)

    run_pending(scheduler);
    sleep(1);

Which corresponds to this Rust interface fn:

#[no_mangle]
pub unsafe extern "C" fn run_pending(ptr: *mut Scheduler) 
    let scheduler = 
        assert!(!ptr.is_null());
        &mut *ptr
    ;

    scheduler
        .run_pending()
        .unwrap_or_else(

Here’s scheduler::run_pending():

    /// Run all jobs that are scheduled to run.  Does NOT run missed jobs!
    pub fn run_pending(&mut self) -> Result<()> {
        //let mut jobs_to_run: Vec<&Job> = self.jobs.iter().filter(|el| el.should_run()).collect();
        self.jobs.sort();
        let mut to_remove = Vec::new();
        for (idx, job) in self.jobs.iter_mut().enumerate() 
            if job.should_run() 
                let keep_going = job.execute()?;
                if !keep_going 
                    debug!("Cancelling job ", job);
                    to_remove.push(idx);
                
            
        
        // Remove any cancelled jobs
        to_remove.sort_unstable();
        to_remove.reverse();
        for &idx in &to_remove 
            self.jobs.remove(idx);
        

        Ok(())
    }

And finally, job::execute():

    /// Run this job and immediately reschedule it, returning true.  If job should cancel, return false.
    ///
    /// If the job's deadline has arrived already, the job does not run and returns false.
    ///
    /// If this execution causes the deadline to reach, it will run once and then return false.
    pub fn execute(&mut self) -> Result<bool> 
        if self.is_overdue(self.now()) 
            debug!("Deadline already reached, cancelling job ", self);
            return Ok(false);
        

        debug!("Running job ", self);
        if self.job.is_none() 
            debug!("No work scheduled, moving on...");
            return Ok(true);
        
        let _ = self.job.as_ref().unwrap().call(); // CALLED RIGHT HERE
        self.last_run = Some(self.now());
        self.schedule_next_run()?;

        if self.is_overdue(self.now()) 
            debug!("Execution went over deadline, cancelling job ", self);
            return Ok(false);
        

        Ok(true)
    

I added a comment where the actual call() happens.

This whole FFI shindig is just an experiment, I don’t actually have a real need for this to work – but now that I got this far, I kinda want to know what I’m getting wrong! Thanks in advance.


Source link

Today I Learned: openat()

This post is originally published on yoursunny.com blog https://yoursunny.com/t/2021/openat/



fopen and open

In C programming language, the <stdio.h> header supplies functions for file input and output.
To open a file, we usually use the fopen function.
It is defined by the C language standard and works in every operating system.

Working at a lower level, there’s also the open function.
It is a system call provided by the Linux kernel and exposed through glibc.

Both fopen and open have an input parameter: the file pathname, as a NUL-terminated string.
These two functions are declared like this:

FILE* fopen(const char* filename, const char* mode);

int open(const char* pathname, int flags);

If the file we want to access is in the current working directory, or we have the full pathname of the file as a string, this is easy to use.
However, sometimes we want to access a file relative to another directory, and the above API isn’t so easy to use.



Directory Path + Filename

One such occasion is in my NDNph library: I wanted to use a directory in the filesystem as a persistent key-value store, where object keys are used as filenames, and object value is written as file content.
The API for this key-value store looks like this:

typedef struct KV KV;

/**
 * @brief Open a key-value store at specified path
 * @param[out] kv key-value store object
 * @param dir directory pathname
 * @return whether success
 */
bool KV_Open(KV* kv, const char* dir);

/**
 * @brief Write @p value to file @p dir "/" @p key
 * @param kv key-value store object
 * @param key filename
 * @param value file content
 * @param size size of file content
 * @return whether success
 */
bool KV_Save(KV* kv, const char* key, const uint8_t* value, size_t size);

Since fopen and open want the file pathname as a single string, I have to concatenate dir and key in KV_Save.
This in turn requires saving a copy of dir in KV_Open function.

typedef struct KV

  char* dir;
 KV;

bool KV_Open(KV* kv, const char* dir)
 !S_ISDIR(st.st_mode)) 
    return false;
  
  kv->dir = strdup(dir);
  return true;


bool KV_Save(KV* kv, const char* key, const uint8_t* value, size_t size)



openat

This week, I came across a new function: openat.
It operates in the same way as open, except that it supports specifying a relative pathname interpreted relative to another directory, which is represented by a file descriptor.

The function signature of openat is:

int openat(int dirfd, const char* pathname, int flags);

This allows me to simplify the key-value store:

typedef struct KV

  int dirfd;
 KV;

bool KV_Open(KV* kv, const char* dir)

  kv->dirfd = open(dir, O_RDONLY 

bool KV_Save(KV* kv, const char* key, const uint8_t* value, size_t size)

  int fd = openat(kv->dirfd, key, O_WRONLY 

KV_Open opens the directory as a file descriptor with the open function.
The O_DIRECTORY flag ensures we are opening a directory instead of a regular file.
It’s no longer necessary to save a copy of the directory path.

KV_Save calls openat with the directory file descriptor and the filename key.
It’s no longer necessary to perform string concatenation.
The code is 5 lines shorter than the open-based solution.



Conclusion and Code Download

This article introduces Linux openat syscall that I recently discovered.
The openat function enables resolving a filename or relative path, relative to another directory that is not the current working directory.
It can do so without requiring manual string concatenation.

Code samples (whole program including load/save/delete functions):

Caution: this proof-of-concept code assumes that key is a valid filename.
It cannot safely handle untrusted and potentially malicious input.


Source link