Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

Is there any difference in the initialization order between such two cases?

Consider this example:

#include <iostream>
struct A {
    A() {
        std::cout<<"hello" << std::endl;
    }
};
inline A a;
int main() {
}

This example causes the program segment under Clang 15, instead

#include <iostream>
struct A {
    A() {
        std::cout<<"hello" << std::endl;
    }
};
static inline A a;
int main() {
}

This example successfully prints hello. In such two cases, the specifier static, IMO, shouldn't affect the initialization order of std::cout and the variable a, the initialization order of them are both indeterminately sequenced, right?

REVIEW: Texas Reckless Cowboy (The Stars of Texas Book 2) by Rebecca Crowley

He’s the bad boy she needs to help her lay down the law…

Assistant District Attorney Georgia Star is on the ballot in Last Stand, Texas to finally take the top job—but popularity has never been this overachiever’s forte. When her big-city outsider opponent begins wooing her constituents with lies, Georgia knows she has to stop playing nice. She turns to the infamous Cy Powell for advice, but his provocative solution might be worse than a defeat.

Cyrus “Cy” Powell is a property mogul, rancher, and entrepreneur—and a scion of Last Stand’s most notorious criminal family. Despite his legit success he’s never outrun his last name, so when Georgia asks for his help, Cy decides a fake relationship is the perfect pretext to infiltrate her world.

Dating Cy will connect Georgia with her voter base, and squiring Georgia through her influential social circles will polish Cy’s reputation and facilitate his latest business deal. Their chemistry is undeniable, but as the election looms, they’ll need to decide if their fake alliance is real and where their loyalties lie.

Dear Ms. Crowley,

Tropes, tropes, get yer tropes here! Small town, friends to lovers, bad boy, across the tracks, fake relationship, (a slight touch of) enemies to lovers, Jewish women in Texas. Wait, what was that last one? It’s the second in The Stars of Texas series about four sisters who are slowly getting back in touch with family and falling for friends in Last Stand, Texas where 150 years ago their Jewish Austrian great … Grandfather put down roots and established himself in a new land.

Georgia Star the ADA in this district is doing what she’s done since getting a job in her hometown – seeking justice rather than trying to be popular. She knows she’s made a few enemies along the way but she’s tried to do her best for everyone she’s seen in court. But now a Hot Shot from out of town has arrived to campaign for the position of District Attorney which Georgia knows is just for show until he can move on to bigger and better political things.

Cy Powell is a certified bad boy from a bad family. The local cops even called the Powell homestead “DFW” (after the largest airport in Texas) since so many of his relatives are frequent flyers through the justice system. Cy uses his reputation for his own purposes but it’s also one he’s been trying to outgrow since he can’t seem to outrun it.

Cy’s (legit) business partner suggests that Cy needs to put in some face time with major bigwigs for the land deals that they’re trying to swing. Looking for someone to give him credibility, Cy devises a plan. If Georgia will be his fake girlfriend, he’ll help her campaign among the outcasts, bikers, rednecks, and other working class rural people of the area whom Hot Shot has spurned. Can Georgia and Cy keep it private and professional until after the election?

The deal that Georgia and Cy have worked out makes a bit more sense to me than other fake dating scenarios. Georgia is really, really bad at campaigning for the position of DA. Cy is really good at hiding his pain and anger at how and what the town thinks of him. She provides the credibility that helps him with the fancy stuff he needs in order to get on the inside of property development deals and he delivers the votes of the barflies and Hermanos Guapos motorcycle gang for her election. To her credit, Georgia does think about this a bit but then decides that telling one little white lie to save her hometown from the city slicker with fancy boots who thinks he can just swoop in for a few years and pander to a few interests then exit to bigger things is something she can do.

For all that they appear as opposites, Cy and Georgia are actually very similar inside. Both feel responsible for family members. Georgia for her three younger sisters and Cy for his younger, feckless, brother. Both also feel like outsiders. Cy because of his ramshackle family and upbringing that caused him to build walls around the trust that he gives to no-one and avoid the pain that giving love would bring. Loyalty is a currency that Cy trades in. And Georgia for her religion and her single-dad father who couldn’t take her to school things which isolated her from peers while she was growing up. Georgia had thought that antisemitism was a thing of the past and not something to affect her in this day and age. To discover how it had shaped her mother’s life is a shock.

Georgia was parentalized at age seven when her mother died. She champions the underdogs and works for real justice for the three counties for which she works. Which might actually work against her in the election as twisted by her opponent. Cy dispenses much needed advice about money and navigating government paperwork to those who have no one else to turn to. They both help their community.

Georgia and her sisters are digging deeper into and having to mentally deal with the antisemitism that separated their mother from her family when mom married their dad and converted. This began in book one, played a minor role here – except for when Georgia out and out calls out a relative for not keeping up with Caroline Star after the family cut Caroline off for marrying a Jewish man. Cy is worrying about his younger brother who might be mixed up in something that threatens the local community.

I liked the way that their similarities bring them together over dealing with the threat to the community. Then I like how this turns into a realistic third act breakup that temporarily pushes them apart. They act in ways that are authentic to how their characters have been built on page. Bonus points that after the initial dust settles, they think about what’s happened, what they want, and, after not storming off nor vowing that they’re done with the other, they offer apologies as they work things out. And though I can take or leave epilogues, this is a nice one. I’m looking forward to the next book in the series. B+

~Jayne

AmazonBNKoboBook DepositoryGoogle

What does it mean by "can be treated as the interface type" in TypeScript handbook?

In the handbook, it says that:

It’s important to understand that an implements clause is only a check that the class can be treated as the interface type. It doesn’t change the type of the class or its methods at all. A common source of error is to assume that an implements clause will change the class type - it doesn’t!

But I don't understand what it means by "can be treated as the interface type" when it also says "It doesn’t change the type of the class or its methods at all."

Does it mean that I need to repeat the exact same types for both the class and the interface?

They give an example where the type of s is any:

interface Checkable {
  check(name: string): boolean;
}
 
class NameChecker implements Checkable {
  check(s) {
    // Notice no error here
    return s.toLowerCase() === "ok";
  }
}

In C++ can you use one empty type as storage for another?

In C++, with reference to the standard, is it safe to use placement new to obtain a pointer to a struct with no members, using another struct with no members as storage? Something like the following:

struct S1 {};
struct S2 {};

S1 s1;
S2* s2 = new (&s1) S2;

The intuitive reason I might expect this to work is that you "can't do anything" with the pointer—there are no members in the struct to access, so there's no way to use this (as far as I can see) to access memory that you shouldn't access. But I'm interested in what the standard says about this, with citations.

Assuming this is fine, is it also fine for any types X and Y such that std::is_empty<X> and std::is_empty<Y> are both true, assuming you don't forget to make an explicit destructor call?


The reason I'm interested in this question is that I have a class like this, which packages up the logic necessary to delay construction of another object:

// A container for an object of type T that can be constructed/destroyed at
// will. This is like std::optional but without the overhead of the presence
// bit.
template <typename T>
class ManuallyConstructed {
 public:
  // Starts uninitialized.
  ManuallyConstructed() = default;
  
  // REQUIRES: not initialized.
  ~ManuallyConstructed() = default;
  
  // Initialize or destroy.
  void Init();
  void Destroy();
  
  // REQUIRES: currently initialized.
  T& operator*();
 
 private:
  // Storage for the object, initialized with placement new by Init.
  alignas(T) char storage_[sizeof(T)];
};

When T is empty according to std::is_empty, I'd like ManuallyConstructed<T> also to be empty. This allows it to benefit from [[no_unique_address]] transparently whenever T would. But it means I need to use an empty type for the storage member, and I still need to be able to provide a T& from the implementation of operator*.

Review: The Case of the Caretaker’s Cat (Perry Mason series book 7) by Erle Stanley Gardner

WHEN THE CAT’S AWAY THE MURDERER WILL PLAY….

In his will, Peter Laxter guaranteed his faithful caretaker a job and a place to live… for life. But Laxter’s grandson Sam says the deal doesn’t include the caretaker’s cat—and he wants the feline off the premises by hook, crook… or poison. When Perry Mason takes the case, he quickly finds there’s much more at stake than an old man’s cat—a million dollars or more to be exact…

Review:

Dear readers,

For years Perry Mason books had been some of my favorite comfort reads. I have read many, many of them in Russian then in English, however I have not reread them in a while. As much as I loved the noble defense lawyer who of course only defends people innocently accused of murder or those who have mitigating circumstances to help the reader feel for them, to me these books do not stand up to rereads as well as say Niro Wolfe and Archie Goodwin series do simply because I remember “who done” it and am not interested as much in rereading the book. However I came across this book on kindle in the Russian translation and it had been years since I first read it and I figured why not try the reread.

And it worked very well for me and a couple of things even surprised me. The first surprise had nothing to do with actual investigation. If you know the books well, you remember that very clear hints of attraction between Mason and his wonderful secretary Della Street run through most of them. I used to imagine that they had a relationship off pages but of course I have no idea if that was what author intended.

In any event the surprise part for me was that in this book at least Mason and Della had to play act as husband and wife as part of the charade Mason decided to play at some point in his investigation to hopefully clear up his client and when they do so, Mason seems to act surprised when Della kisses him. I wonder if this is the book where it all started from. Amazon lists it as book seven, but I am not sure if it was written that early in the series or not.

The investigation itself was a little bit surprising too, but I had seen it in some other books of these series. Mason really does not spend that much time in the courtroom here. Most of the action and investigation takes place outside of it and yes, it all started with a cat :). It still had a lot of fun action and *some* court room time and I enjoyed it all.

The last surprise of the sort for me was that Mason tries to offer some hint about the potential murderer early in the book to Hamilton Burger, District Attorney who is his constant adversary throughout the books. Again, if you read the books you may know that while Mason constantly bests Burger in the court room, Burger is terrified of accusing an innocent person of the crime and when the evidence finally staring him in the face, he always agrees to reopen the investigation, however this book to me features one of the attempts of collaboration between them which happens early enough in the plot of the story. This attempt does not turn out to be very fruitful, but not because Mason tries to conceal anything, he just does not know all the facts yet, still it was interesting to me, I did not see that too often in the series.

Of course everything turns out to be wonderful at the end, as I said comfort read is a comfort read.

Grade: B+

AmazonBNKoboBook DepositoryGoogle

Does the C11 memory model really conflict with common optimizations?

The OP of a recent question added a comment to it linking a paper entitled Common Compiler Optimisations are Invalid in the C11 Memory Model and what we can do about it, which apparently was presented at POPL 2015. Among other things, it purports to show several unexpected and counterintuitive conclusions derived from the specifications for what it calls the "C11 memory model", which I take to consist largely of the provisions of section 5.1.2.4 of the C11 language specification.

The paper is somewhat lengthy, but for the purposes of this question I focus on the discussion of scheme "SEQ" on the second page. This concerns a multithreaded program in which ...

  • a is non-atomic (for example, an int),
  • x and y are atomic (for example, _Atomic int), and
  • a, x, and y all initially have value 0,

... and the following occurs (transliterated from pseudocode):


Thread 1

a = 1;

Thread 2

if (atomic_load_explicit(&x, memory_order_relaxed))
    if (a)
        atomic_store_explicit(&y, 1, memory_order_relaxed);

Thread 3

if (atomic_load_explicit(&y, memory_order_relaxed))
    atomic_store_explicit(&x, 1, memory_order_relaxed);

The paper makes this argument:

First, notice that there is no execution (consistent execution in the terminology of Section 2) in which the load of a occurs. We show this by contradiction. Suppose that there is an execution in which a load of a occurs. In such an execution the load of a can only return 0 (the initial value of a) because the store a=1 does not happen before it (because it is in a different thread that has not been synchronised with) and non-atomic loads must return the latest write that happens before them. Therefore, in this execution the store to y does not happen, which in turn means that the load of y cannot return 1 and the store to x also does not happen. Then, x cannot read 1, and thus the load of a does not occur. As a consequence this program is not racy: since the load of a does not occur in any execution, there are no executions with conflicting accesses on the same non-atomic variable. We conclude that the only possible final state is a=1 ∧ x=y=0.

(Question 1) But isn't that argument fatally flawed?

The assertion that the load of a can only return 0 is made subject to the assumption that a is in fact read, which the argument intends to contradict. But in that case, as the paper observes, there is no happens before relationship between the store to a in thread 1 and the load from a in thread 2. These are conflicting accesses, neither is atomic, and one is a write. Therefore, per paragraph 5.1.2.4/25, the program contains a data race resulting in undefined behavior. Because the behavior is undefined, nothing can be concluded about the value loaded from a by thread 2, and in particular, it cannot be concluded from the specification that the load must return 0. The rest of the argument then collapses.

Although the paper claims that the argument shows that the program does not contain a data race ("is not racy"), in fact that is not a consequence of the argument but rather a hidden assumption. Only if, contrary to 5.1.2.4/25, the program did not contain a data race would the argument stand up.

Now perhaps the key is that the argument above considers only "consistent executions", a term defined in a later section of the paper. I confess that it gets a little deep for me at that point, but if in fact constraining the behavior to consistent executions is sufficient to support the assertion that the load of a must return 0, then it seems that it is no longer (just) the rules of the C11 memory model that we are talking about.

This matters because the authors conclude that a source-to-source translation combining threads 1 & 2 to yield ...


Thread 2'

a = 1;
if (atomic_load_explicit(&x, memory_order_relaxed))
    if (a)
        atomic_store_explicit(&y, 1, memory_order_relaxed);

... is not permitted of implementations by the C11 memory model, on the basis that it allows executions in which the final state is a = x = y = 1. That this and various other code transformations and optimizations are invalid is the thesis of the paper.

(Question 2) But isn't it indeed valid for a C11 implementation to treat the original three-threaded program as if it were the two-threaded program consisting of threads 2' and 3?

If that allows "consistent executions" with results that could not be produced by any consistent execution of the original program, then I think that just shows that C11 does not constrain programs to exhibiting consistent executions. Am I missing something here?

Rocket Lawyer Releases Generative AI Tool, to Help Business Startups, Built in Collaboration with Google Cloud

The online legal services provider Rocket Lawyer today released a generative AI feature, Rocket Copilot, built in collaboration with Google Cloud. 

The company says that Rocket Copilot is an “intuitive, conversational new customer experience” that “combines powerful generative AI with professional human expertise to give customers a simple and fast way to confidently complete their legal documents and other filings alongside convenient access to legal professionals.” 

Today’s initial release of Rocket Copilot offers an AI-powered business name generator to help entrepreneurs name their new businesses. The tool can help entrepreneurs come up with names that are memorable and legally valid,” Rocket Lawyer says. 

Once an entrepreneur chooses a name, they can continue with Rocket Lawyer through the next steps of beginning to form the business entity, registering the trademark, and creating business documents.

“Future releases of Rocket Copilot will include more collaborative brainstorming functionality and continue to securely and responsibly leverage advanced LLM models through Vertex AI, our deep legal knowledge base, and our extensive network of legal professionals to provide our customers with a comprehensive legal support system,” the company says. 

Rocket Lawyer also said that it is expanding its existing partnership with Google Cloud. “The continued collaboration between Rocket Lawyer and Google Cloud brings together the expertise and resources of two industry leaders, ensuring that Rocket Copilot delivers unparalleled value, safety, and security to its customers and network of legal professionals,” the company said. 

“Collaborating with Google Cloud on Rocket Copilot is a testament to our shared commitment to leveraging technology for positive change,” said Charley Moore, Rocket Lawyer founder and CEO. “We believe that our new copilot experience further empowers entrepreneurs and business owners to take control of their legal situations, and we are proud to be at the forefront of this transformative journey.”

Rejected lambda expression

The following lambda expression seems to get rejected by Clang as well as MSVC, while GCC accepts it. Is the expression legal according to C++20 standard?

static_assert([]<int I>() -> decltype([]<int = {I + I}>{ return true; })
    { return {}; }.template operator()<{}>()());

The error message from Clang:

<source>:14:48: error: expected expression
   14 | static_assert([]<int I>() -> decltype([]<int = {I + I}>{ return true; })
      |                                                ^
<source>:15:40: error: expected expression
   15 |     { return {}; }.template operator()<{}>()());
      | 

The error message from MSVC:

<source>(14): error C2065: 'I': undeclared identifier
<source>(15): error C3889: call to object of class type '<lambda_1>': no matching
call operator found
<source>(14): note: could be 'auto <lambda_1>::operator ()(void) const'
<source>(15): note: 'auto <lambda_1>::operator ()(void) const': could not deduce
template argument for '_T1'

Live example

is a c++ array of size N a distinct type [duplicate]

I thought that

int a1[5];

and

int a2[6];

were distinct types.

But

void foo(int a[5]){};
void foo(int a[6]){};

will not compile saying that they are duplicated definitions of foo (ie foo(int *a))

I was very surprised by this. One of the reasons I saw given for why VLAs are not allowed in the c++ standard is because they break the type system.

I was also surprised to find c doing the same thing.

void foo(int a[4]){
   printf("sz=%ld", sizeof(a));
}

reports a pointer size. I expected it to report 4*sizeof(int) (and only accept a variable of type int[4] to be accepted as a call argument)

Is it possible to backport std::byte to C++14

std::byte is defined in C++17 as:

enum class byte : unsigned char {};

I'm currently stuck at using C++14, and I wonder if I add the same definition in C++14 (in some non-std namespace, along with the operator overloads etc.), will this new type get the same aliasing "free-pass" as an unsigned char or I setting myself up for undefined behavior due to violating the strict aliasing rule?

It seems to work, but I'm wondering if I instead should go with using byte = unsigned char; which sadly causes other complications (for instance then I can't make a difference between a byte and uint8_t).

❌
❌